SpringBoot整合WebSocket
一、什么是WebSocket?
WebSocket是一种在单个TCP连接上进行全双工通信的协议。在理解WebSocket之前,我认为有必要说一下Http,以此来对照着理解WebSocket。在以往的Web开发中,通常是客户端(比如网站)调用服务端的接口来请求数据,在这次的前后端交互中,客户端是主动的,客户端通过Http请求来调用服务端接口,以此来获取数据,当数据拿到后,意味着本次的交互结束。这样的话,大家应该知道了,Http是客户端主动请求服务端数据,那么有没有一种技术,能够实现服务端主动向客户端推送数据呢?答案是肯定的,因此诞生了WebSocket协议,它是一种长久的,保持联系的交互方式,一旦客户端与服务端建立联系后,服务端便可实现与客户端的双向通信,并且一直保持着连接状态,直到客户端关闭连接为止。下面通过代码的方式来介绍WebSocket,本次的代码使用Springboot来实现,对Springboot还不了解的同学可以先行学习Springboot。
二、导入WebSocket依赖
<!--webSocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--工具类-->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
</dependency>
三、新建配置类,开启WebSocket支持
要想在SpringBoot项目中开启WebSocket,需要新建一个配置类。
/**
* @作者 yangs
* @日期 2022/1/10
* @描述 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
四、新建WebSocket服务器
这个类其实就是WebSocket服务器,@ServerEndpoint注解配置的路径,供客户端连接。当项目启动后,WebSocket服务器也会启动,届时客户端就可通过我们配置的路径,与WebSocket建立连接,实现双向通信。WebSocket服务器提供了4个核心方法,被@OnOpen、@OnClose、@OnMessage、@OnError注解标注,当建立连接时、断开连接时、收到客户端信息时、发生错误时调用。
/**
* @作者 yangs
* @日期 2022/1/10
* @描述 webSocket服务器
*/
@ServerEndpoint(value = "/wsServer/{userId}")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收userId
private String userId = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
//加入set中
} else {
webSocketMap.put(userId, this);
//加入set中
addOnlineCount();
//在线数加1
}
System.out.println("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
try {
sendMessage("我是服务端,你连接成功了!");
} catch (IOException e) {
System.out.println("用户:" + userId + ",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
System.out.println("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("用户消息:" + userId + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (StringUtils.isNotBlank(message)) {
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId", this.userId);
String toUserId = jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
} else {
System.out.println("请求的userId:" + toUserId + "不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("用户错误:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
System.out.println("发送消息到:" + userId + ",报文:" + message);
if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
System.out.println("用户" + userId + ",不在线!");
}
System.out.println();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
上述代码提供了一个自定义的sendInfo(String message, String userId)方法,可以实现WebSocket向指定客户端推送数据,感兴趣的同学可以尝试调用一下,向某个客户端发送信息。实例:
/**
* @作者 yangs
* @日期 2022/1/10
* @描述 WebSocket服务端主动向客户端推送数据
*/
@RestController
@RequestMapping("/wsMessage")
public class WsMessageController {
/**
* @作者 yangs
* @日期 2022/1/10
* @描述 webSocket服务端向其客户端推送数据
*/
@GetMapping("/pushToCustomer")
public void pushToCustomer(@RequestParam String toUserId, @RequestParam String message) throws IOException {
WebSocketServer.sendInfo(message, toUserId);
}
}
五、编写客户端代码
客户端代码通过js实现,如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>长连接</title>
</head>
<body>
<p>【userId】:
<div><input id="userId" name="userId" type="text" value=""></div>
<p>【toUserId】:
<div><input id="toUserId" name="toUserId" type="text" value=""></div>
<p>【contentText】:
<div><input id="contentText" name="contentText" type="text" value="这是我发的消息"></div>
<p>【操作】:
<div><a onclick="openSocket()" style="cursor: pointer;">开启socket</a></div>
<p>【操作】:
<div><a onclick="sendMessage()" style="cursor: pointer;">发送消息</a></div>
</body>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
var socket;
function openSocket() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
var socketUrl = "http://localhost:4432/nld/wsServer/" + $("#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.onopen = function () {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
/* socket.onclose = function () {
console.log("websocket已关闭");
};*/
//发生了错误事件
socket.onerror = function () {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
}
}
</script>
</html>
总结
以上便是SpringBoot整合WebSocket的全部代码,建议条件允许的同学按照上述代码运行一遍,看看效果。感谢阅读!