一、广播式

  广播式即服务端有消息时,会将消息发送给所有连接了当前endpoint的浏览器

  1.配置websocket,需要在配置类上使用@EnableWebSocketMessageBroker开启websocket支持,并通过继承AbstractWebSocketMessageBrokerConfigurer类,重写其方法来配置websocket

@Configuration
@EnableWebSocketMessageBroker                //1
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override
public void registerStompEndpoints(StompEndpointRegistry registry) {  //2
registry.addEndpoint("/endpointWisely").withSockJS();
registry.addEndpoint("/endpointChat").withSockJS();//3
} @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {  //4
registry.enableSimpleBroker("/queue","/topic"); //5
} }
1. 通过@EnableWebSocketMessageBroker注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样。
2. 注册STOMP协议的节点(endpoint),并映射的指定的URL
3. 注册一个STOMP的endpoint,并指定使用SockJS协议
4. 配置消息代理(Message Broker)
5. 广播式配置一个/topic消息代理
 @Controller
public class WsController { @MessageMapping("/welcome")
@SendTo("/topic/getResponse")
public WiselyResponse say(WiselyMessage message) throws Exception {
Thread.sleep(3000);
return new WiselyResponse("Welcome, " + message.getName() + "!");
} @Autowired
private SimpMessagingTemplate messagingTemplate;// @MessageMapping("/chat")
public void handleChat(Principal principal, String msg) { //
if (principal.getName().equals("wyf")) {//
messagingTemplate.convertAndSendToUser("wisely",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
} else {
messagingTemplate.convertAndSendToUser("wyf",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
}
}
}
1. 当浏览器向服务端发送请求时,通过@MessageMapping("/welcome")映射/welcome这个地址,类似于@RequestMapping
2. 当服务端有消息时,会对订阅了@SendTo中的路径的浏览器发送消息

 2. 脚本代码如下:ws.html

 <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Boot+WebSocket+广播式</title> </head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似你的浏览器不支持websocket</h2></noscript>
<div>
<div>
<button id="connect" onclick="connect();">连接</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的名字</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">发送</button>
<p id="response"></p>
</div>
</div>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
<script type="text/javascript">
var stompClient = null; function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
} function connect() {
var socket = new SockJS('/endpointWisely'); //1
stompClient = Stomp.over(socket);      //2
stompClient.connect({}, function(frame) {  //3
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/getResponse', function(respnose){ //4
showResponse(JSON.parse(respnose.body).responseMessage);
});
});
} function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
} function sendName() {
var name = $('#name').val();  //5 stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));
} function showResponse(message) {
var response = $("#response");
response.html(message);
}
</script>
</body>
</html> 1. 连接SockJs的endpoint名称为“/endpointWisely”
2. 使用STOMP子协议的websocket客户端
3. 连接websocket服务端
4. 通过stompClient.subscribe订阅/topic/getResponse目标发送的消息,这是由@SendTo定义的
5. 通过stompClient.send向/welcome目标发送消息,这是由@MessageMapping定义的

  3. 配置viewController

 @Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws").setViewName("/ws");
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/chat").setViewName("/chat");
} }

最新文章

  1. VS中使用svn注意事项
  2. awk同时处理多个文件
  3. Activity生命周期(一) 暨 帮助文档的使用
  4. Js 一些方法(一)
  5. javap生成的字节码
  6. 百度地图 &gt;&gt; 自定义控件
  7. 【解决】python2.x版本的Django下admin管理页面css无效
  8. 【c语言】统计一个数二进制中的1的个数
  9. Restful based service 的跨域调用
  10. C#将制定文件夹下的PDF文件合并成一个并输出至指定路径
  11. 补习系列(7)-springboot 实现拦截的五种姿势
  12. 与postman的第一次亲密接触
  13. python爬虫的scrapy安装+pymongo的安装
  14. vue从入门到进阶:指令与事件(二)
  15. Nikitosh 和异或 —— 一道 trie 树的题用可持久化 trie 水 然后翻车了...
  16. 配置CentOS6.5的yum源
  17. 深刻理解this的指向和var 定义的变量的问题
  18. 剑指offer题目记录
  19. vue-cli 项目构建性能分析工具
  20. the interconversion of String and StringBuilder

热门文章

  1. SSH原理记录
  2. 【BZOJ4152】[AMPPZ2014]The Captain 最短路
  3. dubbo zookeeper报错failed to connect to server , error message is:No route to host
  4. Docker的初体验
  5. 向spider中传递参数
  6. 相似性分析之Jaccard相似系数
  7. FineReport---数据集
  8. 个人觉得存成char(12),优于varchar(12)
  9. Storm-源码分析-Topology Submit-Executor
  10. Java中native关键字使用