Namespaces in Socket.IO

Imagine that we are writing a server that can be used by any number of client applications, and those client applications could be using any number of other Socket.IO servers as well. We could be introducing bugs into the client application if we use the same message names as the messages coming from the other Socket.IO servers. To circumvent this issue, Socket.IO uses a concept called namespaces to allow us to segregate our messages so that they don't conflict with other applications.

A namespace is a convenient way to provide a unique endpoint to connect to, and we connect to it using code that looks as follows:

const socket = io.of('/customSocket');
socket.on('connection', function(socket) {
...
});

This code should look familiar because, apart from io.of(...), it's the same code that we used previously to connect to a socket. What may come as a surprise is that our code has already been using namespaces, even though we didn't specify it ourselves. Unless we specify a namespace ourself, our sockets will connect to the default namespace, which is equivalent to io.of('/).

When coming up with a name for your namespace, try to think of something that would be unique and meaningful. One standard I have seen adopted in the past utilizes the company name and the project to create the namespace. So, if your company was called WonderCompany and you were working on Project Antelope, you might use /wonderCompany_antelope as the namespace. Don't just assign random characters since they are hard for people to remember, and this would increase the possibility that they will make mistakes typing it in, meaning that the sockets would not connect.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.222.47