Javascript 关闭连接后如何重新连接到websocket
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13797262/
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
How to reconnect to websocket after close connection
提问by ket
I construct my websocket connection with this code (e.g.):
我用这个代码构建我的 websocket 连接(例如):
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.
我做了一些研究并尝试了几种方法。这个问题无法帮助我:Socket.io reconnect on disconnect? 这是唯一接近我正在寻找的结果。
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.
我之所以要这样做,是为了让用户暂时停止向网络发送数据,一段时间后重新发送。如果没有重新连接,用户必须刷新页面才能重新发送。这可能会导致一些数据丢失。谢谢你。
采纳答案by Jivings
NOTE: The question is tagged
socket.ioso this answer is specifically regardingsocket.io.
As many people have pointed out, this answer doesn't apply to vanilla websockets, which will not attempt to reconnect under any circumstances.
注意:该问题已标记,
socket.io因此此答案专门针对socket.io.
正如许多人指出的那样,这个答案不适用于 vanilla websockets,它在任何情况下都不会尝试重新连接。
Websockets will not automatically try to reconnect. You'll have to recreate the socket in order to get a new connection. The only problem with that is you'll have to reattach your handlers.
Websockets 不会自动尝试重新连接。您必须重新创建套接字才能获得新连接。唯一的问题是您必须重新连接处理程序。
But really, websockets are designed to stay open.
但实际上,websockets 旨在保持开放。
A better method would be to have the server close the connection. This way the websocket will fire an oncloseevent but will continue attempting to make the connection. When the server is listening again the connection will be automatically reestablished.
更好的方法是让服务器关闭连接。这样 websocket 将触发一个onclose事件,但将继续尝试建立连接。当服务器再次侦听时,连接将自动重新建立。
回答by SzG
When the server closes the connection, the client does nottry to reconnect. With some JS frameworks maybe, but the question was, at the time of this answer, tagged as plain Vanilla JS.
当服务器关闭连接时,客户端不会尝试重新连接。可能使用一些 JS 框架,但问题是,在这个答案的时候,标记为普通的 Vanilla JS。
I'm a bit frustrated because the accepted, upvoted answer is plainly wrong, and it cost me some additional time while finding the correct solution.
我有点沮丧,因为接受的、赞成的答案显然是错误的,而且在找到正确的解决方案时花费了我一些额外的时间。
Which is here: Reconnection of Client when server reboots in WebSocket
回答by Pol
I found the best solution on this page: sam-low.com
我在此页面上找到了最佳解决方案:sam-low.com
Once the original connection has been closed, you need to create a new WebSocket object with new event listeners
关闭原始连接后,您需要使用新的事件侦听器创建一个新的 WebSocket 对象
function startWebsocket() {
var ws = new WebSocket('ws://localhost:8080')
ws.onmessage = function(e){
console.log('websocket message event:', e)
}
ws.onclose = function(){
// connection closed, discard old websocket and create a new one in 5s
ws = null
setTimeout(startWebsocket, 5000)
}
}
startWebsocket();
Note that if there's a problem reconnecting, the new WebSocket object will still receive another close event, meaning that onclose()will be executed even if it never technically opened. That's why the delay of five seconds is sensible - without it you could find yourself creating and destroying thousands of websocket connections at a rate that would probably break something.
请注意,如果重新连接出现问题,新的 WebSocket 对象仍将接收另一个关闭事件,这意味着onclose()即使它从未在技术上打开过也会被执行。这就是为什么延迟五秒是合理的 - 没有它,您会发现自己以可能会破坏某些东西的速度创建和破坏数千个 websocket 连接。
回答by xemasiv
Flawless implementation:
完美实现:
var socket;
const socketMessageListener = (event) => {
console.log(event.data);
};
const socketOpenListener = (event) => {
console.log('Connected');
socket.send('hello');
};
const socketCloseListener = (event) => {
if (socket) {
console.error('Disconnected.');
}
socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', socketOpenListener);
socket.addEventListener('message', socketMessageListener);
socket.addEventListener('close', socketCloseListener);
};
socketCloseListener();
To test it:
要测试它:
setTimeout(()=>{
socket.close();
},5000);
Edit: Take note of the Exponential Backoff implementation (at the linked thread by top comment: https://stackoverflow.com/a/37038217/8805423), not in above code BUT VERY VERY CRUCIAL.
编辑:注意指数退避实现(在顶部评论的链接线程中:https: //stackoverflow.com/a/37038217/8805423),不在上面的代码中,但非常非常重要。
Edit again: Check out backfrom primus: https://www.npmjs.com/package/back, it's a flexible sexy implementation.
再次编辑:看看back来自primus:https://www.npmjs.com/package/back,它是一种灵活的性感的实现。
回答by Zibri
function wsConnection(url){
var ws = new WebSocket(url);
var s = (l)=>console.log(l);
ws.onopen = m=>s(" CONNECTED")
ws.onmessage = m=>s(" RECEIVED: "+JSON.parse(m.data))
ws.onerror = e=>s(" ERROR")
ws.onclose = e=>{
s(" CONNECTION CLOSED");
setTimeout((function() {
var ws2 = new WebSocket(ws.url);
ws2.onopen=ws.onopen;
ws2.onmessage = ws.onmessage;
ws2.onclose = ws.onclose;
ws2.onerror = ws.onerror;
ws = ws2
}
).bind(this), 5000)
}
var f = m=>ws.send(JSON.stringify(m)) || "Sent: "+m;
f.ping = ()=>ws.send(JSON.stringify("ping"));
f.close = ()=>ws.close();
return f
}
c=new wsConnection('wss://echo.websocket.org');
setTimeout(()=>c("Hello world...orld...orld..orld...d"),5000);
setTimeout(()=>c.close(),10000);
setTimeout(()=>c("I am still alive!"),20000);
<pre>
This code will create a websocket which will
reconnect automatically after 5 seconds from disconnection.
An automatic disconnection is simulated after 10 seconds.

