Socket.io 1.4
Object.keys(io.sockets.sockets);
给您所有连接的插座。
Socket.io 1.0
从socket.io 1.0开始,实际接受的答案不再有效。因此,我做了一个小功能,可以用作临时修复程序:
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;
}
Api for No名称空间变为
// 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');
命名空间的 Api 变为:
// 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');
另请参阅此相关问题,在该问题中,我提供了一个函数,该函数返回给定房间的套接字。
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 :
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
对于命名空间
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
注意:由于socket.io API似乎容易崩溃,并且某些解决方案依赖于实现细节,因此可能需要自己跟踪客户端:
var clients = [];
io.sockets.on('connect', function(client) {
clients.push(client);
client.on('disconnect', function() {
clients.splice(clients.indexOf(client), 1);
});
});