Cover by Mike Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Chapter 10. Activities in Real Time

We are going to be using Node.js’s events library to listen for friend changes from within our Socket.io channel. This gets us around having to subscribe to multiple channels (which isn’t possible) and opens an avenue for scaling out the chat function using something like Redis or RabbitMQ.

This command tells you how many sockets are in a room:

var clients = io.sockets.clients(nick.room)

Adding Custom Events

In Chapter 2 you learned about the events library that ships with Node.js. Events are at the core of JavaScript’s power and Node.js makes it easy to create, trigger, and consume everything from I/O progress to user input to custom actions you define yourself in your functions.

Why are custom events so important for real-time notification in the social networking application? After all, you could very easily trigger an event every time someone logs in, updates his status, or comments on someone else’s profile, and let the event handler decide which connected sockets should see the event.

Because Node.js is single-threaded, any logic you do in your event handler will effectively block your running code. So while it might be fast to process a login event if you have only two connections open from your development computer, if you have a real running site your server will be spending a lot of time going through all of the connections to figure out who a particular message should be sent to. That would be a lot of wasted time when it is just as easy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required