I have a websocket client (for example, a web browser) connected to a websocket server. When the server closes the connection, how can I attempt to reconnect from the client?

Some websocket frameworks like socket.io will handle this for you out the box, but if you’re using the native WebSocket object in the browser you need to do it yourself.

Once the original connection has been closed, you need to create a new websocket object with new event listeners:


var SERVER = 'ws://localhost:8080'
var ws = new WebSocket(SERVER)

ws.onmessage = function(e){
  console.log('websocket message event:', e)
}

ws.onclose = function(){
  console.log('The server closed the connection')
  var new_ws = new WebSocket(SERVER)
  new_ws.onmessage = function() {...}
  new_ws.onclose = function() {
    // don't copy and paste this it's a terrible idea
    console.log('The server closed the connection again!')
    var new_new_ws = new WebSocket(SERVER)
    new_new_ws.onclose = function(){
      console.log('The server closed the connection again! again!')
      var new_new_new_ws = new WebSocket(SERVER)
      // ...repeat forever :D
    }
  }
}

Probably not a great idea to keep writing new WebSocket creations by hand forever and ever though. This is a pretty clear opportunity to abstract everything into a recursive function that executes itself in the event that the socket closes.


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.