Socket.io joins rooms when reconnecting

I am writing a new SPA application that will subscribe to multiple numbers for several types of information updates.

In my production installation, I will use two servers with load balancing for reliability.

In the event of a disconnection - should the client resubmit the request for subscribing to numbers in the reconnection callback, or is there a way for the server to automatically connect to the client (even when the client reconnects to another server to server failure)?

+4
source share
3 answers

Socket.io . . . redis , , . , .

, . , . , , . , , , , , .... /, :

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

... . , .?

+5

Socket.io reconnect -

-

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

:

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

+1

In my experience, I found this the easiest and most 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 here it is. Very simple and straightforward.

You can also add a few updates to the connected socket (last function) for the user screen, for example, update its index or something else.

0
source

All Articles