Rooms and namespaces help organize users in real-time apps. They let you group users to send messages only to some, not everyone.
0
0
Room and namespace concepts in Node.js
Introduction
You want to create chat groups where only members see messages.
You want to separate users by topics or interests in a live app.
You want to reduce network traffic by sending events only to certain users.
You want to create private areas in a multiplayer game.
You want to manage different parts of your app with separate event handlers.
Syntax
Node.js
const io = require('socket.io')(server); // Namespace example const chat = io.of('/chat'); chat.on('connection', (socket) => { // Join a room socket.join('room1'); // Send message to all in room1 chat.to('room1').emit('message', 'Hello room1!'); });
Namespaces start with a slash and separate different parts of your app.
Rooms are inside namespaces and group sockets for targeted messaging.
Examples
This creates a separate namespace for news and a room for sports fans.
Node.js
const io = require('socket.io')(server); // Create a namespace '/news' const news = io.of('/news'); news.on('connection', (socket) => { socket.join('sports'); news.to('sports').emit('update', 'Sports news!'); });
This uses the default namespace and joins a room called 'general'.
Node.js
io.on('connection', (socket) => { socket.join('general'); io.to('general').emit('welcome', 'Welcome to general room!'); });
Sample Program
This program creates a server with a '/chat' namespace. When a user connects, they join 'room1'. Messages sent by a user are broadcast only to others in 'room1'.
Node.js
const http = require('http'); const server = http.createServer(); const { Server } = require('socket.io'); const io = new Server(server); // Create a namespace '/chat' const chat = io.of('/chat'); chat.on('connection', (socket) => { console.log('User connected to /chat namespace'); // Join room 'room1' socket.join('room1'); // Listen for messages from this socket socket.on('sendMessage', (msg) => { // Send message to all in 'room1' chat.to('room1').emit('message', msg); }); }); server.listen(3000, () => { console.log('Server listening on port 3000'); });
OutputSuccess
Important Notes
Namespaces help separate concerns, like chat vs notifications.
Rooms are dynamic and sockets can join or leave anytime.
Use rooms to send messages only to interested users, saving bandwidth.
Summary
Namespaces divide your app into sections with separate event handling.
Rooms group users inside namespaces for targeted messaging.
Use them to organize real-time communication efficiently.