Socket.io: correct way to connect server to client

I am creating a MEAN application with socket.io. When the page is just loaded, the socket connection is established and maintained in real time as the user navigates to different pages due to the single page nature of the application.

User information is available on my socket connection thanks to passport.socketio .

However, when a user logs in or logs out, I want the connection to be reinitialized, as otherwise the socket will contain stale data about the user. Currently I tried to implement it this way: when a user logs in / from outside, the server disconnects that particular client socket by calling socket.disconnect();

.

On the client side, I listen to the event disconnect

and try to reestablish the connection, like:

  _socket.on('disconnect', function(reason) {
     _socket.connect();
  });

      

Ok, now when a user logs out or disconnects, the server disconnects the client, that client connects back, and the user's information in the juice is updated. So far so good.

But consider another case where the connection is broken: the server is restarted. Previously, it "just worked": when I stop my server, the connection drops, but when I start the server again, the connection is automatically restored. But after I added my call _socket.connect();

, it doesn't work anymore: the connection still works until I refresh the page in the browser.

I checked that when the server is disconnect();

, reason

for the disconnect

handler: io server disconnect

. And when the server is stopped, the reason is as follows: transport close

.

So, I applied my disconnect handler like this:

  _socket.on('disconnect', function(reason) {
     if (reason === 'transport close'){
        // don't do anything special
     } else {
        _socket.connect();
     }
  });

      

Now it works. But it all seems like an absolute dirty hack. At least reason

( io server disconnect

and transport close

) seem to be just human-readable strings, so they might change in the future and this will cause my code to stop working. And, well, there must be a better way to do it; I must be missing something important, but unfortunately I cannot find good documentation on socket.io.

So the question is, what is the correct way to connect a server to a specific client?

Also, if you have any resource recommendations to learn about socket.io, I would really appreciate it.

+3


source to share





All Articles