让你的SpringBoot快速添加Websocket
1. 一个demo (可CV食用)
1.1 maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
1.2 配置类 WebsocketConfig
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
1.3 Websocket服务连接管理类
@Component
@ServerEndpoint("/websocket")
public class WebsocketConn {
public final static Map<String, WebsocketConn> WEBSOCKET_CONNECTS = new ConcurrentHashMap<>();
private String name;
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
name = session.getRequestParameterMap().get("name").get(0);
WEBSOCKET_CONNECTS.put(name, this);
}
@OnClose
public void onClose() {
WEBSOCKET_CONNECTS.remove(name);
}
@OnMessage
public String onMessage(String message) {
System.out.println("收到:" + message);
return "收到了你的消息:" + message;
}
public static void send(String name, String message) {
Optional.ofNullable(WEBSOCKET_CONNECTS.get(name)).ifPresent(x -> x.session.getAsyncRemote().sendText(message));
}
}
2. 原生websocket测试前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket测试页</title>
</head>
<body>
<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket('ws://localhost:12000/websocket?name=test');
}
else {
alert('当前浏览器 Not support websocket')
}
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
}
websocket.onmessage = function (event) {
console.log('订阅到数据:', event.data)
setMessageInnerHTML(event.data);
}
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
}
window.onbeforeunload = function () {
closeWebSocket();
}
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket() {
websocket.close();
}
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
3. 实际开发的问题与解决方法
欢迎评论区留言自己遇到的问题或者更好的解决办法
- 用户的websocket连接管理
- 如果用户的唯一标识比较简单,类似demo里,就可以参考上面的实现方式:用map将用户名标识和具体的websocket连接一一对应,发送消息的也是用上面的静态send方法。
- 如果用户的唯一标识复杂,仅靠url不方面传参,可以尝试在onMessage方法里让用户发送一个复杂的唯一标识和初始化内容。
- 报错:[TEXT_FULL_WRITING]
详细报错提示:The remote endpoint was in state [TEXT_FULL_WRITING] which is an invalid state for called method 频繁使用或多线程使用 getAsyncRemote().sendText() 可能会异常,优化后的send方法:
@SneakyThrows
public synchronized void send(String message) {
session.getBasicRemote().sendText(message);
}
public static void send(String name, String message) {
Optional.ofNullable(WEBSOCKET_CONNECTS.get(name)).ifPresent(x -> x.send(message));
}
|