Connect connector in disconnect event

I am trying to reconnect a socket after the disconnect event fires with the same socket.id, here is my socket configuration

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, when disconnecting, I want to reconnect the disconnected user with the same socket.id, if possible

 socket.on('disconnect',function(){ var disconnect_id = socket.id; //i want reconnect the users here }); 
+7
websocket sockets
source share
1 answer

By default, Socket.IO does not have server-side logic for reconnecting. This means that every time the client wants to connect, a new socket object is created, so it has a new identifier. This is for you to implement reconnection.

To do this, you will need a way to save something for this user. If you have any authentication (for example, a passport) - using socket.request you will have an initial HTTP request before updating. Therefore, from there you can store all cookies and data.

If you do not want to store anything in cookies, the easiest way is to send back to the client information about yourself when connecting. Then, when the user tries to connect again, 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 that this is just a sample, and you need to implement something a little better :) Perhaps send the information as a request parameter or save it differently - whatever works for you.

+6
source share

All Articles