Spring websocket 超时设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25930285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring websocket timeout settings
提问by user3135996
I'm using the Spring websocket support. My question is how to set the websocket connection timeout. Now the connection is closed automatically after several minutes. I want the connection never to be closed.
我正在使用 Spring websocket 支持。我的问题是如何设置 websocket 连接超时。现在连接会在几分钟后自动关闭。我希望连接永远不会关闭。
Here is my websocket handler:
这是我的 websocket 处理程序:
public class MyHandler implements WebSocketHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
class MyTimerTask extends TimerTask {
private WebSocketSession session;
public MyTimerTask(WebSocketSession session) {
this.session = session;
}
@Override
public void run() {
try {
String msg = ((int)(Math.random()*50)) + "";
this.session.sendMessage(new TextMessage(msg.toString()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Autowired
private UserDao userDao;
@Autowired
private JdbcDaoImpl jdbcDaoImpl;
private Timer timer;
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
System.out.println("websocket????");
timer = new Timer();
timer.schedule(new MyTimerTask(session), 0, 1000);
logger.info("logger connection");
}
@Override
public void handleMessage(WebSocketSession session,
WebSocketMessage<?> message) throws Exception { }
@Override
public void handleTransportError(WebSocketSession session,
Throwable exception) throws Exception { }
@Override
public void afterConnectionClosed(WebSocketSession session,
CloseStatus closeStatus) throws Exception {
System.out.println("websocket????");
timer.cancel();
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
my websocket config:
我的 websocket 配置:
<websocket:handlers>
<websocket:mapping path="/myHandler" handler="myHandler"/>
</websocket:handlers>
<bean id="myHandler" class="com.sdp.websocket.MyHandler"/>
and javascript client:
和 javascript 客户端:
var webserver = 'ws://localhost:8080/authtest/myHandler';
var websocket = new WebSocket(webserver);
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function (evt) { onClose(evt) };
websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
function onOpen(evt) {
console.log("Connected to WebSocket server.");
}
function onClose(evt) {
console.log("Disconnected");
}
function onMessage(evt) {
console.log('Retrieved data from server: ' + evt.data);
}
function onError(evt) {
console.log('Error occured: ' + evt.data);
}
debugger;
function sendMsg(){
websocket.send("{msg:'hello'}");
}
回答by Bogdan
The websocket stays opened until either the server or the client decide to close it. However, websockets are affected by two timeouts:
websocket 一直保持打开状态,直到服务器或客户端决定关闭它。但是,websockets 受两个超时的影响:
- HTTP session timeout;
- proxy connection timeouts;
- HTTP 会话超时;
- 代理连接超时;
If all you have between your client and your server is a websocket connection, and you don't interact over HTTP with AJAX or requesting other pages, the HTTP session expires and some servers decide to invalidate it along with the websocket (Tomcat7 had a bug that did just that). Some other servers don't do that because they see there is activity on the websocket. See here for an extended discussion: Need some resolution or clarification for how and when HttpSession last access time gets updated.
如果您的客户端和服务器之间只有一个 websocket 连接,并且您没有通过 HTTP 与 AJAX 交互或请求其他页面,则 HTTP 会话将过期,一些服务器决定将其与 websocket 一起失效(Tomcat7 有一个错误)就是这样做的)。其他一些服务器不这样做,因为他们看到 websocket 上有活动。有关扩展讨论,请参见此处:需要解决或澄清 HttpSession last access time 更新的方式和时间。
The other timeout is with proxies. They see the connection and if there is no activity on the wire for a longer period of time, they just cut it because they think it hanged. To address this, while you don't send actual application data, you need to have a heartbeat or a ping/pong of messages from time to time to let the proxy know that the connection is still OK.
另一个超时是使用代理。他们看到了连接,如果电线上长时间没有活动,他们就会切断它,因为他们认为它挂了。为了解决这个问题,虽然您不发送实际的应用程序数据,但您需要不时进行心跳或消息的 ping/pong 以让代理知道连接仍然正常。
Other issues might also intervene, like a buggy browser support for websocket, how your network is configured, firewall rules, etc.
其他问题也可能会产生影响,例如浏览器对 websocket 的支持有问题、网络配置方式、防火墙规则等。
For available timeout options in Spring see the websocket documentation: Configuring the WebSocket Engine.
有关 Spring 中可用的超时选项,请参阅 websocket 文档:配置 WebSocket 引擎。

