服务端
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类 WebSocketConfig,注入ServerEndpointExporter 服务端点出口
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
编写 WebSocketServer 前端访问 /imserver/{userId} 建立一个TCP 连接
@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {}
WebSocketServer里维护一个ConcurrentHashMap,key为userId,value是一个WebSockertServer , 这个里面有 session,@OnOpen(建立连接),@OnClose(关闭连接),@OnMessage(向客户端发送消息),@OnError(监听错误消息)
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
客户端(浏览器)
var socketUrl="http://localhost:9999/demo/imserver/"+$("#userId").val();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
console.log(socketUrl);
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
创建 socket
socket.onopen //打开
socket.onmessage // 获取服务端的消息
socket.onclose // 关闭
socket.onerror // 监听错误事件
socket.send // 向服务端 发送消息
参考文章链接