Reader small image

You're reading from  Socket.IO Cookbook

Product typeBook
Published inOct 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781785880865
Edition1st Edition
Languages
Right arrow
Author (1)
Tyson Cadenhead
Tyson Cadenhead
author image
Tyson Cadenhead

Tyson Cadenhead works as a senior JavaScript engineer at Aloompa in Nashville, Tennessee. He has dedicated his professional career to building large-scale applications in JavaScript and Node. Tyson addresses audiences at various conferences and programming meetups on how to build real-time web applications with Socket.IO or Meteor.js. He blogs on topics such as JavaScript and web technologies at http://www.tysoncadenhead.com. Tyson lives in the greater Nashville area with his wife and two sons, where he enjoys gardening, raising chickens, reading philosophy and economics books, and playing guitar.
Read more about Tyson Cadenhead

Right arrow

Chapter 4. Building a Room with a View

In this chapter, we will cover the following recipes:

  • Creating chat channels with namespaces

  • Joining rooms

  • Leaving rooms

  • Listing the rooms that the socket is in

  • Creating private rooms

  • Setting up a default room

Introduction


Socket.IO uses namespaces to keep separate types of messages from colliding with each other. With namespaces, we can be sure that our applications are listening for the correct events.

We can also define arbitrary rooms that our sockets can join or leave. These rooms restrict someone from receiving messages and send them only to interested parties.

In this chapter, you will also learn how to harness namespaces and rooms to create richer real-time experiences.

Creating chat channels with namespaces


Namespaces are a great way to make sure that our Socket.IO events are not emitted globally to all the sockets that are connected to the server. We can send messages to a namespace. Only the sockets listening to this namespace will receive the event.

Many applications have multiple customers that should never be mixed together. In our URLs, we typically show the use of different domains to keep our customers separate so that customer1.website.com has a different result to customer2.website.com. In the same way, our Socket.IO sockets can be namespaced to minimize concerns about intermingling data and messaging.

In this recipe, we will set up two separate groups of chat channels. We can post to either group. The message will be restricted to the namespace for that group.

Our interface will be a split page with two separate groups. We can post to either group. The messages will show up after that group, as shown in the following screenshot:

Getting ready

For...

Joining rooms


In addition to namespaces, we can also use rooms in Socket.IO to ensure that our messages are only being delivered to the correct sockets.

Although each socket can only have a single namespace, these sockets can belong to multiple rooms. You can think of rooms as channels that a socket subscribes to in order to receive specific types of messages.

For example, if we built a programming application, the user may be interested in JavaScript and Node messages, but not Ruby or C#. With rooms, we can allow users to send messages to specific channels so that only the interested parties will receive it.

As rooms can only be joined if we know the name of the room, it creates a sort of sudo-security. But it is a bit of a hack because if someone can guess the room name and it is exposed to the client to join, they can join any arbitrary room.

In this recipe, we will demonstrate how a user can join a room.

Getting ready

In this recipe, we will use jQuery for some simple DOM manipulation.

How...

Leaving rooms


A socket can not only join a room but also leave any room that it is a member of.

This is important if you're building a real-time application. Here, users may want to disable certain notifications. By leaving a room entirely, the client-side socket will never receive the events that are broadcasted to the room that it has left.

In this recipe, we will expose a single room to the client-side sockets. We will allow the room to be joined or remain separate by simply toggling a checkbox.

The server side will emit a message every two seconds with an ongoing count of how many times the notification has been sent. Therefore, we will be able to turn the notifications on and see the notification numbers logged one after another in a particular order. Then, we can turn it off for a few seconds and finally turn it back on and see the notification number resume after skipping the numbers it would have emitted when it was off.

Getting ready

In this recipe, we will use a little jQuery for the...

Listing rooms the socket is in


Socket.IO provides a dynamic list of the rooms that each socket is a member of. We can retrieve this list and use it as needed.

In this recipe, we will create a list of the rooms that our socket is in. The list will be dynamically updated if the socket leaves any of its rooms.

Getting ready

As usual, this recipe will use jQuery for the DOM manipulation and event delegation.

How to do it…

To list the rooms that your socket is in, follow these steps:

  1. On the server, we will add our socket to three distinct groups by default. We will add an event listener that will request to list the rooms for us. When this event is sent, we will emit a response message that contains socket.rooms, which is an array that Socket.IO builds dynamically as you join and leave rooms. Take a look at the following code:

    io.on('connection', function (socket) {
    
        socket.join('room1');
        socket.join('room2');
        socket.join('room3');
    
        socket.on('list.rooms', function () {
            socket...

Creating private rooms


It can often be useful to provide privacy for certain rooms. This allows you to send messages to a small group of sockets without worrying about the messages being received by sockets that should not be allowed to see them.

Although Socket.IO doesn't have any inbuilt way to consider a room private or public, we can add some logic around joining a room so that only sockets that validate against a password check are allowed to be members of the room.

In this recipe, we will create a simple login page. Sockets can log in with the static password: pass123, but we could easily make it use a dynamic password that comes from our database or an environmental variable. When the socket joins a group, it will be able to see all the messages that are emitted to this group as expected.

Getting ready

For this recipe, we will use jQuery for the DOM manipulation.

We will also make use of the MD5 Node module to hash our password. Although it may seem silly to hash a password that is hardcoded...

Setting up a default room


In Socket.IO, every socket that makes a connection is assigned a default room to emit messages. This default room could be used for a wide variety of purposes.

A practical use of the default room is to store friends or followers of the socket. When another socket joins the default room of a socket, we can assume that the socket is interested in receiving updates from the room that it has joined.

Other sockets are able to join the default room of any other socket. It isn't safe to assume that the default room of a socket only has one member unless the server-side architecture is set up in this way.

In this recipe, we will let our socket emit messages to the default room of any other connected socket. We will build a drop-down list that displays all of our sockets. Also, the client can select the socket that it wants to emit messages to.

Getting ready

For this recipe, we will use jQuery for the event delegation and DOM manipulation.

How to do it…

To emit messages to the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Socket.IO Cookbook
Published in: Oct 2015Publisher: PacktISBN-13: 9781785880865
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Tyson Cadenhead

Tyson Cadenhead works as a senior JavaScript engineer at Aloompa in Nashville, Tennessee. He has dedicated his professional career to building large-scale applications in JavaScript and Node. Tyson addresses audiences at various conferences and programming meetups on how to build real-time web applications with Socket.IO or Meteor.js. He blogs on topics such as JavaScript and web technologies at http://www.tysoncadenhead.com. Tyson lives in the greater Nashville area with his wife and two sons, where he enjoys gardening, raising chickens, reading philosophy and economics books, and playing guitar.
Read more about Tyson Cadenhead