Search code examples
node.jssocketssocket.ioreconnect

Given a user reconnects to the server (using socket.io), how can i rejoin that user to the room he belonged to?


The problem is the following:

A user connects to the server with a specific socketId, and is placed with a partner on a specific room. That room is for them two alone, and the room is not reused ever.

However, because of an internet failure, the users disconnect and then reconnect.

My question is, how do i connect the users to the room they were using in the first place when they reconnect?

Problem is when they reconnect their socketId changes, because it is creating a new connection, so i can't use that to identify them. Ip's won't work either, since more than one person can be using the site in the same household, or the same person can have two tabs open.

Thank you.


Solution

  • var room = user1 + user2;
    socket.join(room);
    io.to(room).emit('message', message);
    

    The room can be created based on user's name, here the room is created by concatenating the user's name in ascending order. So that when user A connects to B or vice versa, they are connected to same room i.e AB.