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

Posted

技术标签:

【中文标题】向 Socket.io 中的其他房间发送消息【英文标题】:Send message to other rooms in Socket.io 【发布时间】:2021-09-04 00:34:35 【问题描述】:

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

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

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

【问题讨论】:

这能回答你的问题吗? Socket.io rooms difference between broadcast.to and sockets.in 【参考方案1】:

从特定房间获取带有套接字 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");
  );

【讨论】:

以上是关于向 Socket.io 中的其他房间发送消息的主要内容,如果未能解决你的问题,请参考以下文章