Concept Flow - Broadcasting to rooms
Client connects
Join room
Server receives message
Broadcast to room
Clients in room receive message
Clients connect and join rooms. When a message is sent, the server broadcasts it only to clients in that room.
const io = require('socket.io')(3000); io.on('connection', socket => { socket.on('join', room => { socket.join(room); }); socket.on('message', msg => { io.to('room1').emit('message', msg); }); });
| Step | Event | Socket ID | Room Joined | Message Received | Broadcast Action | Clients Receiving |
|---|---|---|---|---|---|---|
| 1 | Client A connects | A | - | - | - | - |
| 2 | Client A joins room | A | room1 | - | - | - |
| 3 | Client B connects | B | - | - | - | - |
| 4 | Client B joins room | B | room1 | - | - | - |
| 5 | Client C connects | C | - | - | - | - |
| 6 | Client C joins no room | C | - | - | - | - |
| 7 | Client A sends message 'Hello' | A | room1 | Hello | Broadcast to room1 | A, B |
| 8 | Client B sends message 'Hi' | B | room1 | Hi | Broadcast to room1 | A, B |
| 9 | Client C sends message 'Hey' | C | - | Hey | Broadcast to room1 | A, B |
| 10 | Client C does not receive messages | C | - | - | - | - |
| Variable | Start | After Step 2 | After Step 4 | After Step 6 | After Step 9 |
|---|---|---|---|---|---|
| Socket A rooms | [] | [room1] | [room1] | [room1] | [room1] |
| Socket B rooms | [] | [] | [room1] | [room1] | [room1] |
| Socket C rooms | [] | [] | [] | [] | [] |
Broadcasting to rooms in Express with Socket.io:
- Server joins clients to rooms with socket.join('roomName')
- Server broadcasts with io.to('roomName').emit(event, data)
- Only clients in that room receive the message
- Clients not in the room do not get the broadcast
- Useful for group chats or segmented messagingchatroom using Socket.IO's io object?io.to(room).emit(event, data) to send messages to a room.socket.join('room1');
io.to('room1').emit('greet', 'Hi Room 1!');
What will happen when this code runs?socket.join('room1') adds the current client to the room named 'room1'.socket.join('roomA');
io.to('roomA').emit('update', 'New data');
socket.leave('roomA');
io.to('roomA').emit('update', 'More data');room1 and room2. Which code correctly broadcasts to both rooms without sending duplicate messages to clients in both rooms?io.to('room1').to('room2') sends to clients in either room without duplicates.Pass the test and this pattern moves unknown