Using the disconnect event

Our app is only capturing connection and joining events. Remember that the connection happens automatically, as we do not check the client at all. As soon as the client's io.connect() is called, a connection event is fired. Then, when we change the text input, a join event is fired, which goes to all the other clients. Nothing happens when someone leaves.

Socket disconnection events are different than regular HTTP events. Because HTTP is request based, we never really know when someone leaves; we just know what their last request was. Users usually have to take an action to leave, for example, going to the logout page. Socket.IO creates and maintains a persistent connection, so we will know immediately when someone leaves. Let's add it to our application.

We will begin at the backend. Open app.js and add a new listener for the disconnect event:

socket.on('disconnect', function(){
    socket.broadcast.emit('userDisconnect', {username: socket.username});
  });

There isn't really too much that is new. We know about event listeners, how to get data attached to a socket, and how to broadcast it to everyone but yourself.

Now, we have to go to the client and add the listener there. Add the following to our list of functions:

socket.on('userDisconnect', function(data){
    addLi(data.username + ' has left :(');
});

This function is similar to the others we have written. It just takes the passed in username and adds a new list item to the list. Connect some users and then refresh the page, and you should get some disconnection events, which are shown in the following screenshot: