How to reconnect after you called .disconnect()

The standard approach in latest socket.io is:

socket.on('disconnect', function() {
    socket.socket.reconnect();
}

This is what I've been using in my app and works great. It also ensures that the socket keeps trying to reconnect if the server goes way, and eventually reconnects when the server is back online.

In your case, you need to ensure two things:

  1. You create your socket only once. Don't call socket = io.connect(...) more than once.
  2. You setup your event handling only once - otherwise they will be fired multiple times!

So when you want to reconnect the client, call socket.socket.reconnect(). You can also test this from the browser console in FireFox and Chrome.


You can reconnect by following client side config.

 // for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true };

I'm doing this way with socket.io 1.4.5 and it seems to work, for now:

var app = {
    socket: null,
    connect: function() {
      // typical storing of reference to 'app' in this case
      var self = this;
      // reset the socket
      // if it's not the first connect() call this will be triggered
      // I hope this is enough to reset a socket
      if( self.socket ) {
        self.socket.disconnect();
        delete self.socket;
        self.socket = null;
      }
      // standard connectiong procedure
      self.socket = io.connect( 'http://127.0.0.1:3000', { // adapt to your server
        reconnection: true,             // default setting at present
        reconnectionDelay: 1000,        // default setting at present
        reconnectionDelayMax : 5000,    // default setting at present
        reconnectionAttempts: Infinity  // default setting at present
      } );
      // just some debug output
      self.socket.on( 'connect', function () {
        console.log( 'connected to server' );
      } );
      // important, upon detection of disconnection,
      // setup a reasonable timeout to reconnect
      self.socket.on( 'disconnect', function () {
        console.log( 'disconnected from server. trying to reconnect...' );
        window.setTimeout( 'app.connect()', 5000 );
      } );
    }
} // var app


app.connect();