socketio how to get clients room code example

Example 1: socket emit to specific room using nodejs socket.io

io.on('connection', socket => {  socket.on('disconnecting', () => {    const rooms = Object.keys(socket.rooms);    // the rooms array contains at least the socket ID  });  socket.on('disconnect', () => {    // socket.rooms === {}  });});

Example 2: rooms in socket io

io.on('connection', socket => {
  socket.join('some room');
});
//And then simply use to or in (they are the same) when broadcasting or emitting:

io.to('some room').emit('some event');
//You can emit to several rooms at the same time:

io.to('room1').to('room2').to('room3').emit('some event');
//In that case, an union is performed: every socket that is at least in one of the rooms will get the event once (even if the socket is in two or more rooms).
//You can also broadcast to a room from a given socket:

io.on('connection', function(socket){
  socket.to('some room').emit('some event');
});

Tags:

Misc Example