前言
最近有个新需求,做一个实时通讯的功能,类似于在线聊天这种场景的业务,最后使用WebSocket实现
一、WebSocket简介
WebSocket 是一种网络传输协议,可在单个 TCP 连接上进行全双工通信,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输。
二、配置WebSocket
pom文件
<!-- webSocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.3.9</version>
</dependency>
@Component
public class WebSocketConfig {
/**
* 使用内部容器,需要配置一个Bean
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
三、后端代码示例(服务端)
该注解是将类定义为一个WebSocket服务端,注解值{serverId}用于监听用户连接的URL标识,每个客户端标识不一致,客户端可以通过这个地址访问服务端
@ServerEndpoint("/websocket/{serverId}")
需要用到的字段
//与客户端通信
private Session session;
//客户端标识
private String serverId;
//所有连接服务的客户端,线程安全
private static ConcurrentHashMap<String, WebSocketService> webSocketSet = new ConcurrentHashMap<>();
@OnOpen
public void OnOpen(@PathParam(value = "serverId") String serverId, Session session){
this.session = session;
this.serverId = serverId;
//存放所有的客户端连接,serverId唯一标识
webSocketSet.put(serverId,this);
System.out.println("客户端连接成功,websocket当前连接数为:"+webSocketSet.size());
}
@OnMessage
public void OnMessage(String message){
//message是接收到客户端发来的消息
System.out.println("websocket服务端接收到消息:"+message);
JSONObject json= JSON.parseObject(message);
String msg =json.getString("content"); //需要发送的内容
String receiverId = json.getString("receiverId"); //接收者
String senderId = json.getString("senderId"); //发送者
//这里可以写你的业务代码
//-------------------------
//根据receiverId 找到对应的客户端
WebSocketService service = webSocketSet.get(receiverId);
//判断接收者是否在线
if(service != null){
service.session.getBasicRemote().sendText("需要发送的内容");
}
}
@OnClose
public void OnClose(){
webSocketSet.remove(this.serverId);
System.out.println("客户端退出成功,websocket当前连接数为:"+webSocketSet.size());
}
四、前端代码示例(客户端)
示例使用的vue
data() {
return {
ws: null, //定义websocket对象
}
}
//建立websocket服务
initWebSocket() {
//初始化websocket userId为会话标识
const wsuri = 'ws://127.0.0.1:8080/websocket/'+this.userId;
//连接服务端
this.ws = new WebSocket(wsuri);
//指定事件回调
this.ws.onmessage = this.websocketOnMessage;
this.ws.onopen = this.websocketOnOpen;
this.ws.onerror = this.websocketOnError;
this.ws.onclose = this.websocketClose;
},
//连接建立之后的回调
websocketOnOpen() {
this.ws.send("握手成功");
console.log("--------连接已建立!---------")
},
//数据接收
websocketOnMessage(e) {
console.log("收到了服务端发送的消息"+e)
},
//数据发送
websocketSend(Data) {
//需要把发送者ID,接收者ID发送给服务端,这样服务端才能知道将消息发给谁
this.ws.send(Data);
},
//连接建立失败重连
websocketOnError() {
this.initWebSocket();
},
//关闭
websocketClose(e) {
console.log('断开连接', e);
},