ujwal dhakal
ujwal dhakal

Reputation: 2459

Reconnect socket in disconnect event

I am trying to reconnecct the socket after the disconnect event is fired with same socket.id here is my socket config

var http = require('http').Server(app);
var io = require('socket.io')(http);
var connect_clients = [] //here would be the list of socket.id of connected users
http.listen(3000, function () {
    console.log('listening on *:3000');
});

So on disconnect event i want to reconnect the disconnected user with same socket.id if possible

socket.on('disconnect',function(){
var disconnect_id = socket.id; //i want reconnect the users here
});

Upvotes: 7

Views: 1636

Answers (1)

Andrey Popov
Andrey Popov

Reputation: 7510

By default, Socket.IO does not have a server-side logic for reconnecting. Which means each time a client wants to connect, a new socket object is created, thus it has a new id. It's up to you to implement reconnection.

In order to do so, you will need a way to store something for this user. If you have any kind of authentication (passport for example) - using socket.request you will have the initial HTTP request fired before the upgrade happened. So from there, you can have all kind of cookies and data already stored.

If you don't want to store anything in cookies, the easiest thing to do is send back to client specific information about himself, on connect. Then, when user tries to reconnect, send this information again. Something like:

var client2socket = {};
io.on('connect', function(socket) {
    var uid = Math.random(); // some really unique id :)
    client2socket[uid] = socket;

    socket.on('authenticate', function(userID) {
        delete client2socket[uid]; // remove the "new" socket
        client2socket[userID] = socket; // replace "old" socket
    });
});

Keep in mind this is just a sample and you need to implement something a little bit better :) Maybe send the information as a request param, or store it another way - whatever works for you.

Upvotes: 6

Related Questions