Game Development Reference
In-Depth Information
Understanding Socket.IO rooms
Rooms allow us to partition the connected clients. Rooms allow events to be emitted
to subsets of the connected client list.
Leaving and joining
A user can simply leave or join the room by invoking the following socket functions:
socket.join('room')
socket.leave('room')
If the room does not exist, a new user joins the room, and the room is created. When
the last user leaves the room, then the room is automatically pruned. You do not
need to leave the room at a disconnected event.
Broadcasting an event in the room
The following are the two ways to broadcast a message to all room participants:
We have a socket object of one of the clients in the room:
socket.broadcast.to('room').emit('event_name', data)
This function will not send the data back to the emitting client/socket.
We can also use the io.sockets object directly:
io.sockets.in('room').emit('event_name', data)
This will emit an event, event_name , to all participants in the room.
Getting the room's information
Socket.IO provides us with a powerful set of functions to get the room's information.
They are as follows:
io.sockets.manager.rooms : This is used to get the list of rooms and socket
IDs. It returns a hash with the name of the room as the key and the list of
socket IDs as value.
io.sockets.clients('room') : This will return the array of sockets of the
connected client.
io.sockets.manager.roomClients[socket.id] : This returns the
dictionary of rooms that a particular client socket has joined.
The name of the room that is returned from all the preceding API calls has
a leading / appended to it. It is used by Socket.IO internally, which we
should eliminate.
 
Search WWH ::




Custom Search