Namespaces are a way of separating the business logic of your application while reusing the same TCP connection or minimizing the need for creating new TCP connections for to implement real-time communication between the server and the client.
Namespaces look pretty similar to ExpressJS' route paths:
/home /users /users/profile
However, as mentioned in previous recipes, these are not related to URLs. By default, a single TCP connection is created at this URL http[s]://host:port/socket.io
Reusing the same event names is a good practice when using namespaces. For example, let's suppose that we have a Socket.IO server that we use to emit a setWelcomeMsg event when the client emits a getWelcomeMsg event:
io.of('/en').on('connection', (socket) => { socket.on('getWelcomeMsg', () => { socket.emit('setWelcomeMsg', 'Hello World!') }) }) io.of('/es').on('connection', (socket) => { socket.on('getWelcomeMsg', () => { socket.emit('setWelcomeMsg', 'Hola Mundo!') }) })
As you can see, we defined a listener for the event getWelcomeMsg in two different namespaces:
- If the client is connected to the English or /en namespace, when the setWelcomeMsg event is fired, the client will receive "Hello World!"
- On the other hand, if the client is connected to the Spanish or /es namespace, when the setWelcomeMsg event is fired, the client will receive "Hola Mundo!"