我在我的 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 中执行此操作的最佳方法 - 基本上我需要以最佳性能将消息发送到多个房间。有什么建议?
两个选项:使用 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 足够智能,实际上不会为其他命名空间打开第二个套接字,所以这两种方法在效率上应该相当。
归档时间: |
|
查看次数: |
9225 次 |
最近记录: |