websocket(二)–基于sockjs和stomp实现广播通信
一、简介
原生websocket实现方式需要新版浏览器的支持。为兼容不支持websocket的浏览器,可以使用sockjs和stomp,当浏览器不支持时,会自动改用轮询等方式来模拟websocket实现。这里介绍基于sockjs和stomp实现websocket的广播通信。
二、知识点
2.1 sockjs
sockjs是javascript库,提供了服务器和浏览器间的双向通信,优先使用websocket通信,当浏览器不支持时,则自动改为轮询与服务器通信。
2.2、stomp
stomp(streaming text orientated messaging protocal),即面向流文本的消息协议,定义了服务端与客户端进行消息传递的文本格式,其使用基于帧(frame)的格式定义消息。
三、后端知识点
3.1 注解@EnableWebSocketMessageBroker
开启stomp协议,使用基于消息代理(message broker)来传输,消息的接收支持注解@MessageMapping;
3.2 WebSocketMessageBrokerConfigurer类
定义来自客户端用于配置消息处理如stomp协议的方法,关键方法有:
- default void registerStompEndpoints(StompEndpointRegistry registry)
注册endpoint, 即是客户端连接址。如:registry.addEndpoint("/endpoint").setAllowedOrigins("*").withSockJS(); - default void configureMessageBroker(MessageBrokerRegistry registry)
配置消息代理选项,如接收消息的地址前缀,如:registry.enableSimpleBroker("/topicTalkClient"); - default void configureClientInboundChannel(ChannelRegistration registration)
配置来自客户端的用于接收消息的org.springframework.messaging.MessageChanne。 - default void configureClientOutboundChannel(ChannelRegistration registration)
配置发给客户端的用于发送消息的org.springframework.messaging.MessageChanne。
3.3 @MessageMapping
服务端接收消息的地址(即是客户端发送消息的地址)
3.4 @SendTo
服务端广播的地址(即是客户端监听接收消息的地址);
四、前端知识点
-
需要下载sockjs.js和stomp.min.js
-
连接服务端,如:
var socket = new SockJS("/endpoint");
-
获取stomp对象,如:
client = Stomp.over(socket);
-
连接并订阅消息, 如:
client.connect(headers, function (frame) { client.subscribe("/topicTalkClient", function (response) { ..}) });
-
发送消息,如:
client.send("/topicTalkServer", headers, JSON.stringify({ 'uid': 1, 'msg': msg}));
五、使用示例
5.1 添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
5.2 配置spring mvc类
package com.dragon.public_talk.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/
* 添加静态文件
* @param registry
*/
@Override
public void addResourceHandlers(