前后端分离项目使用WebSocket,报错 The remote party closed the WebSocket connection without completing the close handshake. 怎么解决,或者给一个完整的案例
时间: 2024-05-18 08:11:34 浏览: 321
web项目使用websocket
这个错误通常是由于 WebSocket 连接中断或者关闭时未完成关闭握手导致的。解决方法如下:
1. 检查前后端代码中 WebSocket 的实现是否正确,特别是在连接关闭时是否进行了关闭握手。
2. 检查网络是否稳定,是否存在连接中断的情况。可以使用网络监控工具进行检测。
3. 检查服务器是否存在负载过大的情况,导致 WebSocket 连接被关闭。
下面是一个基于 Spring Boot 的 WebSocket 示例代码,可能对你有帮助:
前端代码(使用 JavaScript):
```javascript
var socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = function() {
console.log('WebSocket connected');
}
socket.onmessage = function(event) {
console.log('Received message: ' + event.data);
}
socket.onclose = function(event) {
console.log('WebSocket closed with code: ' + event.code + ', reason: ' + event.reason);
}
socket.onerror = function(error) {
console.error('WebSocket error: ' + error);
}
```
后端代码(使用 Spring Boot):
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) {
System.out.println("WebSocket connected");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println("Received message: " + message.getPayload());
session.sendMessage(new TextMessage("Hello, " + message.getPayload()));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
System.out.println("WebSocket closed with code: " + status.getCode() + ", reason: " + status.getReason());
}
}
```
这个示例代码实现了一个简单的 WebSocket 服务,前端代码连接到 ws://localhost:8080/ws,后端代码使用 Spring Boot 实现 WebSocketHandler 接口来处理 WebSocket 连接。如果连接关闭时未完成关闭握手,会输出类似如下的错误信息:
```
o.s.w.s.adapter.HttpWebSocketHandlerAdapter : Handling WebSocketMessage failed
java.io.IOException: The remote party closed the WebSocket connection without completing the close handshake.
at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.handleClose(StandardWebSocketSession.java:406) ~[spring-websocket-5.3.13.jar:5.3.13]
at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.doClose(StandardWebSocketSession.java:367) ~[spring-websocket-5.3.13.jar:5.3.13]
at org.springframework.web.socket.adapter.standard.StandardWebSocketSession.close(StandardWebSocketSession.java:310) ~[spring-websocket-5.3.13.jar:5.3.13]
...
```
希望对你有帮助!
阅读全文