Socket.io 1.4
Object.keys(io.sockets.sockets);
daje wszystkie podłączone gniazda.
Socket.io 1.0
Począwszy od socket.io 1.0, rzeczywista zaakceptowana odpowiedź nie jest już poprawna. Zrobiłem więc małą funkcję, której używam jako tymczasowej poprawki:
function findClientsSocket(roomId, namespace) {
var res = []
// the default namespace is "/"
, ns = io.of(namespace ||"/");
if (ns) {
for (var id in ns.connected) {
if(roomId) {
var index = ns.connected[id].rooms.indexOf(roomId);
if(index !== -1) {
res.push(ns.connected[id]);
}
} else {
res.push(ns.connected[id]);
}
}
}
return res;
}
Interfejs API dla braku przestrzeni nazw zostanie zmieniony
// var clients = io.sockets.clients();
// becomes :
var clients = findClientsSocket();
// var clients = io.sockets.clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room');
Interfejs API dla przestrzeni nazw staje się:
// var clients = io.of('/chat').clients();
// becomes
var clients = findClientsSocket(null, '/chat');
// var clients = io.of('/chat').clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room', '/chat');
Zobacz także to pokrewne pytanie , w którym podaję funkcję zwracającą gniazda dla danego pomieszczenia.
function findClientsSocketByRoomId(roomId) {
var res = []
, room = io.sockets.adapter.rooms[roomId];
if (room) {
for (var id in room) {
res.push(io.sockets.adapter.nsp.connected[id]);
}
}
return res;
}
Socket.io 0.7
API bez przestrzeni nazw :
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
Na przestrzeni nazw
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
Uwaga: ponieważ wydaje się, że interfejs API socket.io jest podatny na awarie, a niektóre rozwiązania polegają na szczegółach implementacji, może to być kwestia samodzielnego śledzenia klientów:
var clients = [];
io.sockets.on('connect', function(client) {
clients.push(client);
client.on('disconnect', function() {
clients.splice(clients.indexOf(client), 1);
});
});