关闭连接后如何重新连接到websocket [英] How to reconnect to websocket after close connection
问题描述
var socket = new WebSocket(ws:// 94.12.176.177:8080\" );
然后关闭这个连接:
socket.close();
但是,如何重新建立连接?
我做了一些研究并尝试了几种方法。这个问题不能帮助我:断开连接时socket.io重新连接?
这是接近我所寻找的唯一结果。
我想这样做的原因是允许用户停止向网络临时发送数据,并且一段时间后再次重新发送。如果没有重新连接,用户必须刷新页面才能重新发送。这可能会导致一些数据丢失。谢谢。
您必须重新创建套接字才能重新连接套接字。唯一的问题是你必须重新附加你的处理程序。
但是真的,websocket被设计为保持打开。
更好的方法是让服务器关闭连接。这样,websocket将触发 onclose
事件,但会继续尝试建立连接。当服务器再次收听时,连接将自动重新建立。
I construct my websocket connection with this code (e.g.):
var socket = new WebSocket("ws://94.12.176.177:8080");
And I close the connection with this one:
socket.close();
But how do I reestablish connection?
I've done some research and tried several methods. This question could not help me: Socket.io reconnect on disconnect? It's the only result which close to what I'm looking for.
The reason I want to do this is to allow users to stop sending data to the web temporary, and resending again after a period of time. Without reconnection, user have to refresh the page in order to resend. This may cause some data lost. Thank you.
You'll have to recreate the socket in order to get it to reconnect. The only problem with that is you'll have to reattach your handlers.
But really, websockets are designed to stay open.
A better method would be to have the server close the connection. This way the websocket will fire an onclose
event but will continue attempting to make the connection. When the server is listening again the connection will be automatically reestablished.
这篇关于关闭连接后如何重新连接到websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!