use*_*996 5 spring timeout websocket
我正在使用Spring websocket支持.我的问题是如何设置websocket连接超时.现在连接几分钟后自动关闭.我希望永远不要关闭连接.
这是我的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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的websocket配置:
<websocket:handlers>
<websocket:mapping path="/myHandler" handler="myHandler"/>
</websocket:handlers>
<bean id="myHandler" class="com.sdp.websocket.MyHandler"/>
Run Code Online (Sandbox Code Playgroud)
和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'}");
}
Run Code Online (Sandbox Code Playgroud)
Bog*_*dan 14
websocket保持打开状态,直到服务器或客户端决定关闭它.但是,websockets受两个超时影响:
如果您的客户端和服务器之间的所有内容都是websocket连接,并且您不通过HTTP与AJAX交互或请求其他页面,则HTTP会话到期,并且一些服务器决定使其与websocket一起使其无效(Tomcat7有一个bug那就是那个).其他一些服务器不这样做,因为他们看到websocket上有活动.请参阅此处以获得扩展讨论:需要一些解决方案或澄清HttpSession上次访问时间的更新方式和时间.
另一个超时是代理.他们看到了连接,如果电线上没有活动很长一段时间,他们只是因为他们认为它被绞死而削减它.为了解决这个问题,当您不发送实际的应用程序数据时,您需要不时地发出心跳或ping/pong消息,让代理知道连接仍然正常.
其他问题也可能会介入,例如浏览器支持websocket,网络配置方式,防火墙规则等.
有关Spring中的可用超时选项,请参阅websocket文档:配置WebSocket引擎.
| 归档时间: |
|
| 查看次数: |
21277 次 |
| 最近记录: |