How to reconnect to websocket after close connection
Solution 1
NOTE: The question is tagged
socket.io
so 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.
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.
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.
Solution 2
When the server closes the connection, the client does not try to reconnect. With some JS frameworks maybe, but the question was, at the time of this answer, tagged as plain 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
Solution 3
I found a great solution on this page: sam-low.com
Once the original connection has been closed, you need to create a new WebSocket object with new event listeners
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.
ket
Updated on July 09, 2022Comments
-
ket almost 2 years
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.
-
AHungerArtist over 11 yearsJust make a new WebSocket again. The reason a reconnect doesn't exist is because it would probably be just like creating a new one.
-
Peter Mortensen over 7 yearsPossible duplicate of Reconnection of client when the server reboots in WebSocket.
-
Tomasz Waszczyk about 6 yearsHere is one of the possible solution: github.com/gdi2290/angular-websocket/issues/100
-
-
UpTheCreek almost 11 yearsThe behaviour where the client socket attempts to reestablish the connection - I guess that's a socketio thing? (not a basic websockets thing?)
-
Jivings almost 11 years@UpTheCreek Yes I think so. Normal websockets will not try and reconnect if you call
close()
-
Triynko over 10 yearsI was using an open-source pure AS3 implementation of WebSockets and TLS, but I decided the browser's implementation would be kept more up-to-date, so I created a JS WebSocket manager that my AS3 WebSocket class calls. The manager constructs instances with unique IDs and callbacks that forward the event and the socket ID to static methods in Flash, which then looks up the corresponding AS3 instance and dispatches events on it. This allows me to "reconnect();" without having to reattach event handlers, since the AS3 WebSocket just requests a new JS WebSocket and ID under the hood.
-
SzG almost 8 yearsWhen the server closes the connection, the client DOES NOT try to reconnect. With some JS frameworks maybe, but the question is tagged as plain Vanilla JS.
-
Jivings almost 8 yearsSorry for your frustration. The OP links to a
socket.io
question, and that must have been the framework he was using. The question should be taggedsocket.io
. -
Chad over 7 yearsThank you for the link; it did the trick. The accepted answer did not make sense as I am working on a websocket without a framework.
-
aegyed over 7 yearsThe ansver you point to does essentially the same what @Jivings suggests. Except this one doesnt mention
socket.close
instance method. -
Jochem Schulenklopper about 7 yearsIndeed, having the client do a reconnect after a web socket was closed, needs to be programmed. It's not done automatically. See stackoverflow.com/questions/3780511/… for some examples.
-
Daniel F about 7 yearsAnd there's a good reason for plain vanilla js not auto-reconnecting. Who wants to get his proxy hammered while the websocket server is down? Take your time and implement a reconnection strategy that suits your needs.
-
akauppi over 6 yearsI don't like the way you state it as "flawless implementation". Flawless for what? It's better to let others judge that by the votes. It is clever how you create the socket from within the close handler. Maybe that could be the introductory line, instead.
-
Zibri over 5 yearsyou di NOT answer the question!
-
clarent over 4 yearsWebSocket never trying to reconnect
-
jjxtra about 4 yearsShould not be marked as the answer, please see @SzG answer for correct response.
-
jjxtra about 4 years@Pol answer is simpler and cleaner
-
Ali Alizadeh over 2 yearssorry, is this optimized way?