Managing the socket life cycle

If our server maintains a list of our connected sockets, it should always be mindful of when a socket disconnects.

A socket can disconnect for any number of reasons:

  • The user may navigate away from the web page that the WebSocket connection is on
  • The user's Internet may go down

When these things happen, we can tap into the disconnect event to notify the client side that the socket is no longer available.

How to do it…

To remove references from disconnected sockets, follow these steps:

  1. First, listen for the socket disconnect event on the server side. When this occurs, we will emit an event back to the clients with the ID of the socket that was disconnected. Socket.IO associates every socket with a unique ID, which we can ...

Get Socket.IO Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.