Joining Rooms and Group Chat
🎯 Introduction
Public broadcasts reach all online users. We now want User A and User B to receive each other's messages when they join the same chat room, while keeping different rooms independent. A Socket.IO room groups connections by name so messages can be sent to a specific group.
🧱 Rooms Are Managed on the Server
A room is a collection of connections identified by a room name. Socket.IO creates it when the first connection joins and automatically removes it when the last connection leaves. No separate “create room” API is needed.
The server calls socket.join(name) to join a room and socket.leave(name) to leave it. Clients request these actions through custom events, and the server decides whether to perform them. When a connection closes, Socket.IO automatically removes it from all rooms.
Continue with the previous server.mjs and installed dependencies. Add this code inside the existing connection callback, before the chat listener. Only room1 and room2 are available, and each client chats in just one current room. Socket.IO itself allows a connection to join multiple rooms simultaneously; our single-room convention makes “send to the current chat room” unambiguous.
socket.on('room:join', async (name, reply) => {
if (typeof reply !== 'function') {
return;
}
if (!['room1', 'room2'].includes(name)) {
reply({ ok: false, error: 'This room is not available' });
return;
}
if (socket.data.room && socket.data.room !== name) {
reply({ ok: false, error: 'Leave the current room first' });
return;
}
await socket.join(name);
socket.data.room = name;
reply({ ok: true, room: name });
});
room:join is our custom event name, so the client must send it with emit. The handler checks the room name and current state before calling socket.join(name).
socket.data stores application data for this connection. Here, socket.data.room records the current room name for subsequent send and leave operations. Assigning this field alone does not join a room; join and leave manage actual membership.
Handle Leaving Separately
Add a room:leave listener in the same connection callback.
socket.on('room:leave', async (reply) => {
if (typeof reply !== 'function') {
return;
}
if (socket.data.room) {
await socket.leave(socket.data.room);
socket.data.room = null;
}
reply({ ok: true });
});
When the client emits room:leave, the server leaves the current room and clears the recorded name. Since there are no other application arguments, the acknowledgement function is the listener's first argument. Leaving a room keeps the connection open, so the client can request to join another room.
Send Messages to the Current Room
Replace the previous chat:send listener with this complete version. It adds a check that the client has joined a room and sends messages only to that room.
socket.on('chat:send', (text, reply) => {
if (typeof reply !== 'function') {
return;
}
if (!socket.data.room) {
reply({ ok: false, error: 'Join a room first' });
return;
}
if (typeof text !== 'string' || !text.trim() || text.trim().length > 100) {
reply({ ok: false, error: 'Enter 1–100 characters' });
return;
}
io.to(socket.data.room).emit('chat:message', {
senderId: socket.id,
text: text.trim()
});
reply({ ok: true });
});
Previously, io.emit sent to every connection. Here, io.to(roomName).emit limits recipients to the room, including the sender. Use socket.to(roomName).emit to notify only other connections in that room. Rooms
🛠 Verify Delivery Within Rooms and Isolation Between Rooms
Replace client.mjs with the following code. After connecting, the client first requests to join a room, then sends a message only after a successful acknowledgement.
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
const room = 'room1';
const text = 'Message from User A';
socket.on('chat:message', (message) => {
console.log('Message received', message.text);
});
socket.on('connect_error', (error) => {
console.log('Connection failed', error.message);
});
socket.on('connect', () => {
socket.emit('room:join', room, (result) => {
console.log('Join result', result);
if (!result.ok) {
return;
}
socket.emit('chat:send', text, (reply) => {
console.log('Send result', reply);
});
});
});
Restart the server, run node client.mjs, and keep User A online. Copy the file to client-b.mjs, change text to “Message from User B”, then change room according to the table and run node client-b.mjs. Stop the previous User B process before each change.
| User B's room | User A (room1) | User B |
|---|---|---|
| room1 | Receives “Message from User B” | Joins successfully, receives its own message, and sends successfully |
| room2 | No new message | Joins successfully, receives its own message, and sends successfully |
To test leaving, replace the chat:send call in User B's successful join callback with:
socket.emit('room:leave', (result) => {
console.log('Leave result', result);
});
After restarting, it should print Leave result { ok: true }. The connection stays open but no longer receives new messages from that room.
❓ Questions and Answers
Q1: Does knowing a room's name give a user permission to join?
The server must also check application permissions. For a private group chat, for example, check whether the user belongs to the group before calling join. This example only checks whether the room is available, so any connected client can choose room1 or room2.
Q2: Does joining the same room again cause duplicate messages?
Each connection has only one membership entry per room. Repeatedly joining the same room does not produce duplicate broadcasts through duplicate membership. If messages repeat, check for multiple emit calls or multiple listeners that print messages.
🧪 Exercise
Change the actions following User B's successful join callback to verify each case:
- After joining room1, request room2 directly. Expect “Leave the current room first”, with the client still in room1.
- After joining room1, request to leave, wait for success, then request room2. Joining should succeed.
- Join, leave, wait for success, then send a chat message. Expect “Join a room first”.
Restart User B after each change so each experiment begins with a new connection.
🎉 Different chat rooms can now share one service while receiving their own messages.
