Skip to content
yads edited this page Oct 10, 2014 · 12 revisions

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 and Leaving

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 to a room

There are two ways for emitting to a room: either using socket.broadcast.to('room') or io.sockets.in('room').

##Socket Broadcast

Broadcasts are sent from a socket object and are received by all clients in the room except for the emitting socket

io.sockets.on('connection', function (socket) {
  socket.broadcast.to('room').emit('event_name', data) //emit to 'room' except this socket
})

A broadcast is sent to all sockets except for the emitting one if a room is not specified

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('event_name', data) //emit to all sockets except this one
})

##Io Sockets

Emitting an event to all clients in a particular room

io.sockets.in('room').emit('event_name', data)

Emitting an event to all clients

io.sockets.emit('event_name', data)

Emitting an event to all clients in a namespace of a particular room

io.of('namespace').in('room').emit('event_name', data)

Getting information about rooms

All rooms

A list of all rooms can be found by looking in io.sockets.adapter.rooms. This is a hash, with the room name as a key to an array of socket IDs. To find the rooms for a different namespace call io.of('namespace').adapter.rooms.

Rooms a client has joined

You can get an array of rooms a particular client socket has joined by looking in socket.rooms.

It is important to note that all clients are automatically joined to a room with the same id as the socket. This is the default room for the socket.

Clone this wiki locally