Socket.IO 消息传递到多个房间

Joe*_*oel 4 node.js socket.io

我在我的 Node Express 应用程序中使用 Socket.IO,并使用这篇优秀文章中描述的方法来关联我的套接字连接和会话。在评论中,作者描述了一种向特定用户(会话)发送消息的方法,如下所示:

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!');
});
Run Code Online (Sandbox Code Playgroud)

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

mts*_*tsr 7

两个选项:使用 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");
Run Code Online (Sandbox Code Playgroud)

使用命名空间:

// 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")
Run Code Online (Sandbox Code Playgroud)

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

  • 我认为这些相当于我已经在做的识别每个用户的工作。也就是说,每个用户根据他的会话密钥获得他自己的 socket.io 通道,我向该通道广播以便发送给该用户(而不是直接在一个套接字上发射)。所以我的问题是:如果这些用户中的两个(每个由一个房间代表)需要接收相同的消息,有没有一种有效的方法来做到这一点? (4认同)
  • 最后一点不应该是`io.of('/chat/channel-name') (3认同)