socket.io rejoin rooms on reconnect

Socket.io will unsubscribe your users from all rooms on a disconnect. It will unsubscribe you from the server side. I played around with this a little. The server can store your user's rooms in redis or a database under the user ID and, upon connecting, check to see if that user should be in any of these rooms. At which time your user can join them from the server side without ever having to do anything from the client.

The problem is that this list of rooms must be constantly stored and updated. It's just another thing that has to work seamlessly on the backend. It's a lot of tests to consider all the possibilities that could mess up your organization. Like, what if they log in on another device, you have to clear the rooms and put in new ones, but if the user opens his laptop again and it reconnects, now he has to get back in those rooms from his laptop. ...It's totally doable/solvable, but I only did this on the front end:

  // rejoin if there's a disconnect
  mySocket.on('reconnect', () => {
    mySocket.emit('subscribe', 'theRoom')
  })

...and no further hassle. If you added some more details about why it's necessary to do it from the server..?


From my experience, I found this to be the easiest and useful solution:

Client side:

// the next 3 functions will be fired automatically on a disconnect.
// the disconnect (the first function) is not required, but you know, 
// you can use it make some other good stuff.

socket.on("disconnect", function() {
  console.log("Disconnected");
});

socket.on("reconnect", function() {
  // do not rejoin from here, since the socket.id token and/or rooms are still
  // not available.
  console.log("Reconnecting");
});

socket.on("connect", function() {
  // thats the key line, now register to the room you want.
  // info about the required rooms (if its not as simple as my 
  // example) could easily be reached via a DB connection. It worth it.
  socket.emit("registerToRoom", $scope.user.phone);
});

Server side:

io.on('connection', function(socket){
      socket.on("registerToRoom", function(userPhone) {   
    socket.join(userPhone);   
  });
});

And thats it. Very simple and straight forward.

You also can add in the connected socket (the last function) some more updates to the user display, such as refreshing its index or something else.


Socket.io does have a reconnect event - Docs here

Something like the below should work

socket.on('reconnect', () => attemptReconnection())

The attempt reconnection callback would look something like:

const attemptReconnection = () => socket.emit('joinRoom', roomId)

Tags:

Socket.Io