-
Notifications
You must be signed in to change notification settings - Fork 0
Rooms
Rooms allow simple partitioning of the connected clients. This allows events to be emitted to subsets of the connected client list, and gives a simple method of managing them.
Joining a named room is achieved by calling the join() function on a connected socket object.
socket.join('room')
Leaving a room is achieved by calling the leave() function on a connected socket object.
socket.leave('room')
A simple subscribe/unsubscribe system can be built very quickly.
socket.on('subscribe', function(data) { socket.join(data.room); })
socket.on('unsubscribe', function(data) { socket.leave(data.room); })
Note that it is not necessary to call socket.leave() during the disconnect event. This will happen automatically. Empty rooms will be automatically pruned so there is no need to manually remove them.
Emitting an event to all clients in a particular room
io.sockets.in('room').emit('event_name', data)
A list of all rooms can be found by looking in io.sockets.manager.rooms. This is a hash, with the room name as a key to an array of socket IDs. Note that the room names will have a leading / character. This is used internally and does not have to be referenced when joining, leaving or emitting to rooms.
If you want a list of clients in a particular room, call io.sockets.clients('room'). This will return the socket IDs of all clients in the room.
You can get a list of rooms a particular client socket has joined by looking in io.sockets.manager.roomClients[socket.id]. Again, the room name will have a leading / character.
It is important to note that all clients are automatically joined to a room with a blank name. This is a catch-all room that contains a list of all connected clients. It will show up as a key with a value of "" in lists of room names.