Node.js Socket.io Namespaces, Rooms and Connections 02

Video Tutorial

Overview

As we have covered in the last video tutorial the basic emit and listen methods of sockets on a specific server where all the connected sockets will be able to listen for event emitted on the server without an exception, well this could be a hustle especially when trying to make chat or VoIP apps since it requires more tools to control the traffic going from one socket to another and among the main point server and the connected sockets.

Therefore there are whats called Namespaces and Rooms where you can create each namespace for your application for taking care of a very specific job (gaming namespace, news namespace…) and many more examples so you would know how data can travel between two connected users and can actually reach to both of them safely protecting users privacy and data.

Rooms are part of namespaces where each namespace can be divided into several rooms and a very room handles a certain type of sockets (Join & Leave) it basically works by a socket (user) sends a join request to one of the available rooms and the server joins it in the room (it could need authentication or invitation depending on your application).

Socket.io Namespaces 

A namespace is basically a route defined on your API (/games) and upon connection, the request has to be sent to the specific namespace route let’s say the server is running on our localhost and we want to join the games namespace so we simply request a socket io connection to (localhost:3000/games) and thus all the connected sockets to one namespace would can reach sockets on the same namespace but can’t talk with other namespace’s socket.

Let’s Create that on our server.

//Use the of method on the io library to select a specific namespace (create it)
io.of("/games").on("connection", socket => {
  //Welcome new joiners!
  socket.emit("welcome", "This is the Gaming Channel!");
}

We create a new namespace simply by selecting it (io.of(namespace)) and adding the connection listener for it, then whenever the client wants to connect instead of hitting the root route (localhost:3000/) it needs to use the namespace name as the route.

Also if you can notice for the namespace name we have to use the forward slash before it either when creating it on the server or when trying to connect from the client’s side.

And make sure to specify the namespace using the io.of method whenever you want to access the sockets or emit/add listeners.

.

As you can clearly see in the structure above that sockets connect to namespaces and more specifically to rooms where each client can have one or more sockets which depends on the client’s needs and requests.

Socket.io Rooms

Rooms are part of a namespace where you can create as many rooms as your application needs to do pretty much everything concerning sockets and exchanging data (for ex: Private Chat) and in order to allow a socket (client) to join a room it first has to be requested then the Server endpoint handler handles the join request and either allow or deny depending on your application whether the client needs an authentication or a specific password or whatever you rely on your code base.

Here is how it could go between the client and the server.

//Keep track of the available Rooms 
let registeredRooms = ["rocket league", "csgo", "bt1"]; 
// Gamers only will understand the rooms list (pretty much a couple of games).
//When the user request to join
socket.on("joinRoom", room => {
  console.log("Joining Room...: " + room);
  if (registeredRooms.includes(room)) {
    //Socket has joined the request room
    return socket.emit("success", "Invalid Room Name: " + room);
  } else {
   //No room with the specified Name! (or it could be another reason).
   return socket.emit("err", "Invalid Room Name: " + room);
  }
}

Once we request (emit) we should also add listeners for both the success and the error events so whenever something happens your application is always ready to receive and log to the console, for a larger applications you may need to create your specific API routes and events so you would know where to request whenever ever you need something from the Server End Point.

Let’s say you also need to inform the other connected clients (sockets) on the room whenever someone new connects, therefore we have used rooms for this kind of specific scenarios.

Select the namespace and the room then emit the event you want to send to all the connected clients and that’s it.

...
/*On Join Room Success Emit newUser event to all connected users including the one who submited the join request*/
io.of("/games").in(room).emit("newUser", "New user has been connected to the " + room + " Room");
...

As you can clearly see we used the root io library here to emit instead of the socket itself, cause the socket only represent one connection (which is the one who sent the join request) but that we actually want is to send a notification event to all the already connected users on the room so they would know a new gamer has been joined them.

Therefore we through the root io library we access the namespace first then we use them in method to tell which room to emit the event on (broadcast) and finally the emit method with the event name and data to send.

For selecting the broadcast room there are two methods (in: sends the event to all the connected sockets including the one who sent the request) and (to: sends the event to all the connected sockets but the one who sent the request) so you can use each one on the right scenario.

Socket.io Connection

The Socket.io library works pretty much the same as Web Sockets but not the same so you won’t be able to use a web socket server with a socket.io client or vice-versa.

The connection between the client and the server is maintained by sending the receiving acknowledgment sockets and if the server goes down the client is gonna keep reconnecting till the server is up again (you can configure it).

Simply for shutting down a client connection to the server either from the client side or from the server side all you need is to access the socket and call the method.

//Either from Server Side or from Client Side you can broke the connection.
socket.shutdown();

What’s Next

Socket.io is a very powerful library with a lot of features that will help you create, manage and manipulate sockets from your server endpoint and for creating real-time data exchange apps.

In the next tutorial, we will cover the creating of a very basic chat application base on Socket.io and Node.js.

No Comments Yet