How to reconnect to websocket after close connection

99,462

Solution 1

NOTE: The question is tagged socket.io so this answer is specifically regarding socket.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.

Share:
99,462
ket
Author by

ket

Updated on July 09, 2022

Comments

  • ket
    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.

  • UpTheCreek
    UpTheCreek almost 11 years
    The behaviour where the client socket attempts to reestablish the connection - I guess that's a socketio thing? (not a basic websockets thing?)
  • Jivings
    Jivings almost 11 years
    @UpTheCreek Yes I think so. Normal websockets will not try and reconnect if you call close()
  • Triynko
    Triynko over 10 years
    I 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
    SzG almost 8 years
    When 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
    Jivings almost 8 years
    Sorry 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 tagged socket.io.
  • Chad
    Chad over 7 years
    Thank 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
    aegyed over 7 years
    The ansver you point to does essentially the same what @Jivings suggests. Except this one doesnt mention socket.close instance method.
  • Jochem Schulenklopper
    Jochem Schulenklopper about 7 years
    Indeed, 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
    Daniel F about 7 years
    And 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
    akauppi over 6 years
    I 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
    Zibri over 5 years
    you di NOT answer the question!
  • clarent
    clarent over 4 years
    WebSocket never trying to reconnect
  • jjxtra
    jjxtra about 4 years
    Should not be marked as the answer, please see @SzG answer for correct response.
  • jjxtra
    jjxtra about 4 years
    @Pol answer is simpler and cleaner
  • Ali Alizadeh
    Ali Alizadeh over 2 years
    sorry, is this optimized way?