2016-05-13 34 views
1

我正在使用更新版本的socket.io,我無法弄清楚如何獲得套接字列表對象。我跟着一些教程和StackOverflow的答案,比如這個:如何獲取socket.io v1 +中連接的套接字對象(不是套接字ID)列表?

How to get all the sockets connected to Socket.io

我也看了一下文檔,但它並沒有太大的幫助。我發現的所有帖子解釋瞭如何獲取socketIds,但我自己需要套接字,所以我可以只發布到某些套接字。

那麼你如何得到實際的套接字本身,或者在新版本的套接字中不再可能呢?

回答

2

你可以有幾個選擇:

// An object with socket.id as property and socket object as value 
// You could iterate this with for/in or use `Object.keys()` to get the ids 
// and then access each socket by id 
// io.sockets.connected 

var ids = Object.keys(io.sockets.connected); 
ids.forEach(function(id) { 
    var socket = io.sockets.connected[id]; 
    // do something with socket here 

}); 

// an array of sockets which you can iterate directly as an array. 
// io.sockets.sockets 

io.sockets.sockets.forEach(function(socket) { 
    // do something with socket here 

}); 

您也可以分別訪問命名空間:

// array of sockets in this namespace 
io.nsps['/'].sockets 

// map of socket ids in this namespace 
io.nsps['/'].connected