【问题标题】:Send message to other rooms in Socket.io向 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

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

【问题讨论】:

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


【解决方案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");
  });

【讨论】:

    猜你喜欢
    • 2022-08-21
    • 2023-03-27
    • 1970-01-01
    • 2019-03-12
    • 2017-09-27
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多