2012-02-13 47 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