Book Image

Building Scalable Apps with Redis and Node.js

By : Joshua Johanan
Book Image

Building Scalable Apps with Redis and Node.js

By: Joshua Johanan

Overview of this book

Table of Contents (17 chapters)
Building Scalable Apps with Redis and Node.js
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...