Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect reconnect event in Socket IO

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?

like image 558
rustyengineer Avatar asked Apr 24 '16 19:04

rustyengineer


1 Answers

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');
});
like image 183
Vikneshwar Avatar answered Nov 22 '22 23:11

Vikneshwar