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 messaging