8

Whenever a client connects, I assign an id to that client using socket.id, and maintain it in the server for future reference. The problem I'm having right now is with disconnect/reconnect. I'm not even sure how to simulate this scenario, because if I reload the client page, it's technically creating a new client and connect to the server with different id. If I disconnect and connect the client manually then the client will again have a different id (socket.id).

I set up 'reconnect' event on both client and server using socket.on('reconnect',function(){...}), but it never seems to get called, given what I tried above.

So how would you go about simulating this scenario? And then what's the best way to detect if this new client is actually the same client that has disconnected?

rustyengineer
  • 343
  • 3
  • 16
  • 1
    I have answered this question already there: http://stackoverflow.com/questions/20260170/handle-browser-reload-socket-io/20261163#20261163 – Are Apr 24 '16 at 19:38
  • Thanks. I actually have thought about this solution, which is emitting an extra event to setup/identify customID for both client/server. I believe it should solve my problem. Just I wonder if I can touch on the reconnect event somehow and see if it suggests any other solution – rustyengineer Apr 24 '16 at 19:46
  • There is no `reconnect` event in socket.io and I'm pretty sure you don't need it when you can implement it on your own :) – Are Apr 24 '16 at 19:59
  • Alright then. I saw it listed as one of the events in clients API so just wondering :). Thanks – rustyengineer Apr 24 '16 at 20:20
  • @AreWojciechowski - Per the [client doc](http://socket.io/docs/client-api/), there is a `reconnect` event on the client socket (scroll to the bottom of that doc page). – jfriend00 Apr 25 '16 at 01:59

1 Answers1

8

There is a reconnect event on the client side inside which you can emit to the server and find the the reconnected client

socket.on('reconnect', function () {
    console.log('you have been reconnected');
    // where username is a global variable for the client
    socket.emit('user-reconnected', username);
});

on the server you can get that as

socket.on('user-reconnected', function (username) {
     console.log(username + ' just reconnected');
});
Vikneshwar
  • 1,029
  • 4
  • 20
  • 38