Spring-boot 2.0 + WebSocket
-
为什么要用WebSocket?
为了在做一些操作后,服务端能主动向客户端提示失败结果,而HTTP协议只能是客户端向服务端发送请求。
而WebSocket就是一个基于TCP的新协议,类似于socket.io;
在服务端和客户端之间建立socket链接以便服务端进行主动推送。
配置过程
pom.xml配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置spring-boot支持
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer服务配置
@ServerEndpoint("/websocket/{id}")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer