你可以有幾個選擇:
// 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