get rooms socket io code example

Example 1: 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');
});

Example 2: socket io get user rooms

function getUserRooms(socket) {
    return Object.entries(rooms).reduce((names, [name, room]) => {
        if (room.users[socket.id] != null) names.push(name)
        return names
    }, [])
}