2012-02-13 79 views
3

我在我的Node Express应用程序中使用Socket.IO,并使用this excellent post中描述的方法将我的套接字连接和会话关联起来。在a comment笔者介绍的方式将消息发送到特定用户(会话)是这样的: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!'); 
}); 

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

回答

4

两种选择:使用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是足够聪明,实际上没有打开第二个插槽用于附加命名空间,两种方法的效率应该相当。

+3

我认为这些相当于我已经在识别每个用户。也就是说,每个用户都根据自己的会话密钥获取他自己的socket.io频道,然后我将该频道广播到该频道以发送给该用户(而不是直接在一个套接字上发射)。所以我的问题是:如果这些用户中的两个(每个都由一个房间代表)需要接收相同的消息,是否有一种有效的方法来执行此操作? – Joel 2012-02-19 14:57:16

+3

最后一位不应该是'io.of('/ chat/channel-name') – Funkodebat 2012-11-04 16:26:08