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:
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 use to manage our sockets. Here is the server-side code:io.on('connection', function (socket) { io.emit('user.add', socket.id); socket.on('disconnect', function () { io.emit('user.remove', socket.id) }); });
Then, add an element to your view that...