【问题标题】:Socket.IO messaging to multiple roomsSocket.IO 向多个房间发送消息
【发布时间】:2012-02-13 15:11:25
【问题描述】:

我在我的 Node Express 应用程序中使用 Socket.IO,并使用this excellent post 中描述的方法来关联我的套接字连接和会话。在a comment,作者描述了一种向特定用户(会话)发送消息的方法,如下所示:

sio.on('connection', function (socket) {
    // do all the session stuff
    socket.join(socket.handshake.sessionID);
    // socket.io will leave the room upon disconnect
});

app.get('/', function (req, res) {
    sio.sockets.in(req.sessionID).send('Man, good to see you back!');
});

似乎是个好主意。但是,在我的应用程序中,我经常会同时向多个用户发送消息。我想知道在 Socket.IO 中执行此操作的最佳方法 - 基本上我需要以最佳性能将消息发送到多个房间。有什么建议吗?

【问题讨论】:

  • 您是否找到了一种好方法(在群组/房间聊天中向不同用户发送相同的消息)。 ?

标签: node.js socket.io


【解决方案1】:

两种选择:使用 socket.io 通道或 socket.io 命名空间。两者都记录在 socket.io 网站上,但简而言之:

使用渠道:

// all on the server
// on connect or message received
socket.join("channel-name");
socket.broadcast.to("channel-name").emit("message to all other users in channel");

// OR independently
io.sockets.in("channel-name").emit("message to all users in channel");

使用命名空间:

// on the client connect to namespace
io.connect("/chat/channel-name")

// on the server receive connections to namespace as normal
// broadcast to namespace
io.of("/chat/channel-name").emit("message to all users in namespace")

因为 socket.io 足够聪明,实际上不会为额外的命名空间打开第二个套接字,所以这两种方法在效率上应该是相当的。

【讨论】:

  • 我认为这些等同于我已经在做的识别每个用户的工作。也就是说,每个用户都根据他的会话密钥获得自己的 socket.io 频道,我向该频道广播以便发送给该用户(而不是直接在一个套接字上发射)。所以我的问题是:如果这些用户中的两个(每个由一个房间表示)需要接收相同的消息,有没有一种有效的方法来做到这一点?
  • 最后一位不应该是 `io.of('/chat/channel-name')
猜你喜欢
  • 2013-08-20
  • 2023-03-27
  • 2018-06-15
  • 1970-01-01
  • 2019-03-12
  • 2017-09-27
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多