给我提供一个springboot方法,要求可以和很多客户端调用WebSocket做长链接,要求可以给客户端发送消息
时间: 2023-11-27 22:52:08 浏览: 58
以下是一个使用SpringBoot框架的WebSocket长连接方法,可以与多个客户端进行通信并且接收和发送消息:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/websocket").setAllowedOrigins("*");
}
private class MyHandler extends TextWebSocketHandler {
private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 接收到消息
String payload = message.getPayload();
// 处理消息
// ...
// 发送消息给所有客户端
for (WebSocketSession webSocketSession : sessions) {
webSocketSession.sendMessage(new TextMessage("Hello, Client!"));
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 新客户端连接
sessions.add(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 客户端断开连接
sessions.remove(session);
}
}
}
```
在客户端可以使用 JavaScript 的 WebSocket 对象连接到服务器,代码如下:
```
let ws = new WebSocket("ws://localhost:8080/websocket");
ws.onopen = function(event) {
console.log("连接成功");
};
ws.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
ws.onclose = function(event) {
console.log("连接关闭");
};
ws.send("Hello, Server!");
```
阅读全文