如何在Java Spring Tomcat中快速关闭无响应的websocket? [英] How do you quickly close a nonresponsive websocket in Java Spring Tomcat?
问题描述
我有一个实时应用程序,客户端使用websockets连接Spring Framework服务器,该服务器运行Spring Boot Tomcat。我希望服务器能够快速(在5秒内)检测到客户端由于网络断开或其他问题而停止响应并关闭websocket。
I have a real-time application with clients using websockets to connect with a Spring Framework server, which is running Spring Boot Tomcat. I want the server to quickly (within 5 seconds) detect when a client stops responding due to a network disconnect or other issue and close the websocket.
我试过
-
将最大会话空闲超时设置为在文档中描述为配置WebSocket引擎
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
@Bean
public WebSocketHandler clientHandler() {
return new PerConnectionWebSocketHandler(ClientHandler.class);
}
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container =
new ServletServerContainerFactoryBean();
container.setMaxSessionIdleTimeout(5000);
container.setAsyncSendTimeout(5000);
return container;
}
我不确定这是正确实现的,因为我没有看到ServletServerContainerFactoryBean和我的一代ClientHandler之间的链接。
I am not sure this is implemented correctly because I do not see the link between the ServletServerContainerFactoryBean and my generation of ClientHandlers.
-
每2.5秒从服务器发送ping消息。通过断开网络连接手动断开客户端后,服务器会愉快地发送ping 30秒以上,直到出现传输错误。
Sending ping messages from server every 2.5 seconds. After I manually disconnect the client by breaking the network connection, the server happily sends pings for another 30+ seconds until a transport error appears.
同时1和2
1和2并设置 server.session-timeout = 5
in application.properties
1 and 2 and setting server.session-timeout = 5
in application.properties
我的测试方法这是:
- 将websocket从笔记本电脑客户端连接到Tomcat服务器
- 关闭使用物理交换机在笔记本电脑上建立网络连接
- 等待Tomcat服务器事件
Spring FrameworkTomcat服务器快速检测到客户端已断开连接或没有响应关闭websocket?
How does a Spring FrameworkTomcat server quickly detect that a client has been disconnected or not responding to close the websocket?
推荐答案
我最终采用的方法是实现应用层乒乓协议。
The approach I eventually took was to implement an application-layer ping-pong protocol.
- 服务器向客户端发送一段期限为
p
的ping消息。 - 客户端使用pong消息响应每条ping消息。
- 如果服务器发送超过
n
ping消息而未收到pong响应,则会生成超时事件。 - 如果客户端在
n * p
时间内没有收到ping消息,也会生成超时事件。
- The server sends a ping message with period
p
to the client. - The client responds to each ping message with a pong message.
- If the server sends more than
n
ping messages without receiving a pong response, it generates a timeout event. - The client can also generate a timeout event if it does not receive a ping message in
n*p
time.
在底层TCP连接中使用超时应该有一种更简单的方法来实现它。
There should be a much simpler way of implementing this using timeouts in the underlying TCP connection.
这篇关于如何在Java Spring Tomcat中快速关闭无响应的websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!