Search code examples
node.jsexpressserversocket.ioclient

Send message to other rooms in Socket.io


I Know how to send message to all the clients in the same room. I am using below code to send message to clients in the same room (server side).

io.to(Array.from(socket.rooms)[1]).emit("send message","We are in Same room")
//Array.from(socket.rooms)[1] -> getting room number from the map

But now I want to send message to All the clients who are not in current room.


Solution

  • Get the array with socket IDs from specific room and using that array to exclude from all connected sockets:

    const socketsFromRoom = Array.from(await io.in("my_room").allSockets());
    
    Array.from(await io.allSockets())
      .filter((socketId) => !socketsFromRoom.includes(socketId))
      .forEach((socketId) => {
        io.sockets.sockets.get(socketId).emit("send_message");
      });