- WebSocket协议是基于TCP的一种新的网络协议。他实现了浏览器与服务器全双工(Full-duplex)通信,即允许服务器自动发送信息给客户端,这样就可以实现从客户端发送消息到服务器;而服务器又可以发送消息到客户端,这样就能够实现两者之间的交互。目前大部分浏览器已经实现了WebSocket协议,但是也有一部分浏览器没有实现WebSocket协议,为了兼容那些没有实现该协议的浏览器,往往还需要通过STOMP协议来完成这些兼容。这篇博客主要针对于SpringBoot+WebSocket来实现消息的发送与处理。
- 首先构建一个springBoot项目,然后引入倚赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 对于WebSocket的使用,可以先通过Spring创建java配置文件。在这个文件中先建ServerEndPointExporter对象,通过他可以定义WebSocket服务器的端点,这样客户就可以请求这个端点,从而实现两者的交互:
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter () {
return new ServerEndpointExporter();
}
}
有了这个Bean,就可以使用@ServerEndpoint注解定义一个服务端类,然后在这个类中定义WebSocket的打开、关闭、错位、发送信息等方法
- 创建服务站点
@ServerEndpoint(value = "/ws/test")
@Component
public class WebSocketServer {
@PostConstruct
public void init() {
System.out.println("websocket已加载");
}
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
public static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
//这里为什么采用这种方式获取bean文章后边有说明
private MySendMessageImpl mySendMessageImpl = (MySendMessageImpl) SpringUtils

本文介绍了如何在SpringBoot项目中使用WebSocket实现全双工通信。内容包括WebSocket协议的作用,浏览器兼容性处理,以及通过SpringBoot配置WebSocket服务器端点,定义打开、关闭、错误和消息处理方法。同时,文章讨论了异步发送消息的必要性,以及在实际操作中遇到的问题和解决方法,最后提供了测试连接的步骤。
最低0.47元/天 解锁文章
342

被折叠的 条评论
为什么被折叠?



