在 Socket.io 中向其他房间发送消息

时间:2021-06-19 17:29:43

标签: node.js express server socket.io client

我知道如何向同一个房间的所有客户发送消息。我正在使用以下代码向同一房间(服务器端)的客户端发送消息。

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

但现在我想向所有不在当前房间的客户发送消息。

1 个答案:

答案 0 :(得分:2)

从特定房间获取带有套接字 ID 的数组,并使用该数组从所有连接的套接字中排除:

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");
  });
相关问题