socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

The right way for a client to reconnect after the server does a socket.disconnect( true )

Open DrLightman opened this issue 10 years ago • 35 comments

Server: node + socket.io

var io = require( 'socket.io' )( 3000 );

io.on( 'connection', function ( socket ) ...

// at some point if client auth fails, server may kick him out:

socket.disconnect( true );

Client: html/js + socket.io 1.4.5

socket = io.connect( 'http://127.0.0.1:3000', {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax : 5000,
    reconnectionAttempts: 99999
} );

socket.on( 'connect', function () {
    console.log( 'connected to server' );
} );

socket.on( 'disconnect', function () {
    console.log( 'disconnected to server' );
} );

The above is simplified but that is the basis. Reconnection works fine if I fire up the client when the server is down. The client tries to connects to the server and when I finally fire up the server the connection is estabilished.

At some point it may happen that the server decides to disconnect the client, mainly because he logged out invalidating the token and a query on the db tells to do so, or the auth token expired or whatever.

IN this circumstance I'd like the restore the server polling by the client because the user may want to login again and he has the rights to connect again to the server.

If I refresh the page (client) in the browser it works okay but it's an ugly solution.

I think the cause is the "Manager.skipReconnect" property set to true after doing disconnect(), so I'm asking what is the proper way to reinitiate a reconnection polling by the client after the server disconnects a client.

Found some answers on stackoverflow about this but all were unsuccessfull, all stuff to be executed in the client:

  • socket.io.reconnect();
  • socket.socket.reconnect(); // ??
  • socket = io.connect( 'http://127.0.0.1:3000', ... // reinvoking the connect snippet seems bad idea

Could you help me about this matter?

Thank you

DrLightman avatar Mar 09 '16 01:03 DrLightman

For now, I managed this way and it seems to be stable:

Client:

var app = {
...
socket: null,
connect: function() {
  var self = this;
  if( self.socket ) {
    self.socket.destroy();
    delete self.socket;
    self.socket = null;
  }
  this.socket = io.connect( 'http://127.0.0.1:3000', {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax : 5000,
    reconnectionAttempts: Infinity
  } );
  this.socket.on( 'connect', function () {
    console.log( 'connected to server' );
  } );
  this.socket.on( 'disconnect', function () {
    console.log( 'disconnected from server' );
    window.setTimeout( 'app.connect()', 5000 );
  } );
}
...
} // var app

DrLightman avatar Mar 09 '16 12:03 DrLightman

Using a similar approach of:

  this.socket = io.connect( 'ws://127.0.0.1:3000', {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax : 5000,
    reconnectionAttempts: Infinity
  } );

Unfortunately, this causes the socket to use http protocol, rather than web sockets.

Still seeking a good approach for a persistent web socket connection.

Have I missed something???

JamieMeyer avatar Oct 08 '16 02:10 JamieMeyer

Also interested in a solution to this.

JulesAU avatar Nov 11 '16 07:11 JulesAU

socket.connect() worked for me on version 1.5.1 . Hope that helps.

sconway avatar Dec 04 '16 19:12 sconway

@sconway Can you enlighten us? Any code may be?

husnulhamidiah avatar Dec 30 '16 10:12 husnulhamidiah

Hi there,

Had the same question, found this solution, currently testing, seems to be either a robust solution or a robust workaround... (both are provided)

http://stackoverflow.com/questions/10437584/socket-io-reconnect

wiill avatar Mar 09 '17 19:03 wiill

Could we get this fixed in socket.io itself?

ramtob avatar Jul 02 '17 09:07 ramtob

I upgraded to version 2.0.3 and its default autoreconnect settings worked, no issues here.

trentkg avatar Jul 14 '17 21:07 trentkg

When whether Server or Client calls to disconnect() method the client destroy the socket, deletes all events handlers and the manager removes it from the connecting array. This won't occurs when the disconnection is for another reason. A great workaround could be read the reason parameter

.on('disconnect', reason => { 
  if(reason === 'io server disconnect') {
    //you should renew token or do another important things before reconnecting
    socket.connect();
  }
});

Or much better check if socket still be in the manager's connecting list

.on('disconnect',  () => {
  if(socket.io.connecting.indexOf(socket) === -1){
    //you should renew token or do another important things before reconnecting
    socket.connect();
  }
})

pablodgonzalez avatar Jul 21 '17 07:07 pablodgonzalez

I did it like @DrLightman and it works perfectly!

var WebSocketServer = {
	isConnected: false,
	socket: null,
	interval: null,
	connect() {
		if (this.socket) {
			this.socket.destroy();
			delete this.socket;
			this.socket = null;
		}
		this.socket = io.connect('http://localhost:9010', {
			reconnection: false
		});
		this.socket.on('connect', () => {
			this.isConnected = true;
			this.socket.emit('authentication', { user_id: 2751, token: "abc" });
			this.socket.on('authenticated', function() {

			});
		});

		this.socket.on('disconnect', () => {
			this.isConnected = false;
			this.interval = window.setInterval(() => {
				if (this.isConnected) {
					clearInterval(this.interval);
					this.interval = null;
					return;
				}
				WebSocketServer.connect()
			}, 5000);
		});

		return this.socket;
	}
}

var socket = WebSocketServer.connect();

jimping avatar Aug 03 '17 06:08 jimping

@DrLightman this is how i do it and works perfectly in browsers or Android/IOS Apps var io= new socketio.connect('http://192.168.43.79:3000',{'forceNew':true});

devyaz avatar Nov 24 '17 12:11 devyaz

@pablodgonzalez i have same question ,your solution is worked?

programmerCs avatar Jan 22 '18 05:01 programmerCs

@programmerCs Yes, It is. In production without detected problems.

pablodgonzalez avatar Jan 23 '18 14:01 pablodgonzalez

This issue cleared a lot of my issues Thanks everyone

chiragiem36 avatar Jan 24 '18 11:01 chiragiem36

Had the same problem when I wanted to force a client to refresh it's token because it expired while connected to the server.

I ended up sending an event to the client instead, asking him to refresh it's token. No socket gets closed by doing this, so it avoids problems and it works fine !

...now it's time to push that to production ! :cold_sweat: :smirk:

wmcmurray avatar Jan 25 '18 05:01 wmcmurray

Seems like the simpliest solution is to listen to 'disconnect' event from emitter and call setTimeout( ) function but what about events which the client can create while it's being disconnected from the server? Seems like it needs always to execute additional check if connection is established before broadcasting any emit on client.

qassa avatar Jan 31 '18 21:01 qassa

@qassa if you need some confirmation about emit, you should use callback parameter. Instead if you need guarantee the reception of an event, you should not use socket.io but some queue library/protocol such as mosquito/mqtt or whatever. the setTimeout is an option but a socket disconnected (by the server or the client) is a socket soon destroyed. So, if you need guarantee easy and fast reconnection why use setTimeout if you have the socket object instance yet and can call connect()?

pablodgonzalez avatar Jan 31 '18 23:01 pablodgonzalez

Someone from the project REALLY NEEDS TO DOCUMENT this...

CxRes avatar Feb 01 '18 19:02 CxRes

Lemme get this straight, does the server disconnect the client for a specific reason or due to loss of network connection? If its just network then Socketio(client) will try indefinitely to re-connect! , if configured like this io=new socketio(‘http://yourserver.com’, {'forceNew':true}); either way it will still reconnect, but if you put a listerner to a disconnect from server, simply call io.disconnect() on client

From: CxRes [mailto:[email protected]] Sent: February 01, 2018 09:50 PM To: socketio/socket.io [email protected] Cc: devyaz [email protected]; Comment [email protected] Subject: Re: [socketio/socket.io] The right way for a client to reconnect after the server does a socket.disconnect( true ) (#2476)

Someone from the project REALLY NEEDS TO DOCUMENT this...

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/socketio/socket.io/issues/2476#issuecomment-362381171 , or mute the thread https://github.com/notifications/unsubscribe-auth/ATfQSQQ1LJ90E6FqsdmiMktpp2AdoLuxks5tQhVQgaJpZM4HsVs7 . https://github.com/notifications/beacon/ATfQSYqwkgtrHZk9FASNZUl69ps9ZYYCks5tQhVQgaJpZM4HsVs7.gif

devyaz avatar Feb 02 '18 08:02 devyaz

@devyaz i love you

paredesivan avatar May 11 '18 18:05 paredesivan