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.
Andrey Popov
source share