Search code examples
javascripthtmlwebsocketsocket.io

How to reconnect to websocket after close connection


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.


Solution

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