7

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 }); 
3
  • It sounds like you're assuming that a socket.id will uniquely identify a user instead of a connection. The server will generate a new id for each connection, and you can't override that. Commented Dec 3, 2015 at 15:14
  • ok if the same socket.id cant be reconnect i want reconnect them with new generated socket id then Commented Dec 3, 2015 at 15:15
  • The default for socket.io-client is to reconnect automatically (documented here, the reconnection option). Commented Dec 3, 2015 at 15:17

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

as in client api gives a number of options for reconect but i was not able to use it due to poor documentation of it so could you help me out?
Uhhh, socket.io does too have logic for reconnecting so your first paragraph seems completely wrong.
My bad, wanted to say sever-side logic. Thanks for pointing it out!
I just stumbled upon this question again. You should either accept the answer, provide your own, or delete the question :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.