node.js Socket.IO - 如何获取连接的套接字/客户端列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6563885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket.IO - how do I get a list of connected sockets/clients?
提问by Andy Hin
I'm trying to get a list of all the sockets/clients that are currently connected.
我正在尝试获取当前连接的所有套接字/客户端的列表。
io.socketsdoes not return an array, unfortunately.
io.sockets不幸的是,不返回数组。
I know I could keep my own list using an array, but don't think this is an optimal solution for 2 reasons:
我知道我可以使用数组保留我自己的列表,但不要认为这是最佳解决方案,原因有两个:
Redundancy. Socket.IO already keeps a copy of this list.
Socket.IO provides method to set arbitrary field values for clients (i.e:
socket.set('nickname', 'superman')) so I'd need to keep up with these changes if I were to maintain my own list.
冗余。Socket.IO 已经保存了这个列表的副本。
Socket.IO 提供了为客户端(即:)设置任意字段值的方法,
socket.set('nickname', 'superman')所以如果我要维护我自己的列表,我需要跟上这些变化。
Help?
帮助?
回答by 3rdEden
In Socket.IO 0.7 you have a clientsmethod on the namespaces, this returns a array of all connected sockets.
在 Socket.IO 0.7 中,您clients在命名空间上有一个方法,它返回所有连接的套接字的数组。
API for no namespace:
无命名空间的 API:
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
For a namespace
对于命名空间
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
Hopes this helps someone in the future
希望这有助于将来的某人
NOTE:This Solution ONLYworks with version prior to 1.0
注意:此解决方案仅适用于 1.0 之前的版本
UPDATED 2020 Mar 06
2020 年 3 月 6 日更新
From 1.x and above, please refer to this link: getting how many people are in a chat room in socket.io
从1.x及以上,请参考这个链接:在socket.io中获取聊天室中有多少人
回答by nha
Socket.io 1.4
Socket.io 1.4
Object.keys(io.sockets.sockets);gives you all the connected sockets.
Object.keys(io.sockets.sockets);为您提供所有连接的套接字。
Socket.io 1.0As of socket.io 1.0, the actual accepted answer isn't valid anymore. So I made a small function that I use as a temporary fix :
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 namespacebecomes
无命名空间的Api变为
// 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 for a namespacebecomes :
命名空间的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');
Also see this related question, in which I give a function that returns the sockets for a given room.
另请参阅此相关问题,其中我提供了一个函数,该函数返回给定房间的套接字。
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
Socket.io 0.7
API for no namespace:
无命名空间的API :
var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`
For a namespace
对于命名空间
var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`
Note:Since it seems the socket.io API is prone to breaking, and some solution rely on implementation details, it could be a matter of tracking the clients yourself:
注意:由于 socket.io API 似乎很容易被破坏,并且某些解决方案依赖于实现细节,因此可能需要自己跟踪客户端:
var clients = [];
io.sockets.on('connect', function(client) {
clients.push(client);
client.on('disconnect', function() {
clients.splice(clients.indexOf(client), 1);
});
});
回答by salihcenap
After socket.io 1.0 we cannot use
socket.io 1.0 之后就不能用了
io.sockets.clients();
or
io.sockets.clients('room');
anymore. Instead you can use the following
了。相反,您可以使用以下内容
var clients_in_the_room = io.sockets.adapter.rooms[roomId];
for (var clientId in clients_in_the_room ) {
console.log('client: %s', clientId); //Seeing is believing
var client_socket = io.sockets.connected[clientId];//Do whatever you want with this
}
回答by Joseph Dykstra
Using Socket.IO 1.x:
使用 Socket.IO 1.x:
Get array of the connected clients:
获取已连接客户端的数组:
io.engine === io.eio // => true
Object.keys(io.engine.clients) // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]
Object.keys(io.eio.clients) // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]
Get the number of connected clients:
获取连接的客户端数量:
io.engine.clientsCount // => 2
io.eio.clientsCount // => 2
回答by or29544
Very simple in socket.io 1.3:
在 socket.io 1.3 中非常简单:
io.sockets.sockets- is an array containing the connected socket objects.
If you stored the username in each socket, you can do:
io.sockets.sockets- 是一个包含连接的套接字对象的数组。如果您将用户名存储在每个套接字中,您可以执行以下操作:
io.sockets.sockets.map(function(e) {
return e.username;
})
Boom. You have the names of all connected users.
繁荣。您拥有所有连接用户的名称。
回答by Thanh Nguyen
I've gone through this pain today. Socket.io will be much better if they could make a proper documentation for their API.
我今天经历了这种痛苦。如果 Socket.io 能为他们的 API 制作适当的文档,他们会好得多。
Anyway, I tried to look into io.sockets and found a number of options we can use:
无论如何,我尝试查看 io.sockets 并找到了许多我们可以使用的选项:
io.sockets.connected //Return {socket_1_id: {}, socket_2_id: {}} . This is the most convenient one, since you can just refer to io.sockets.connected[id] then do common things like emit()
io.sockets.sockets //Returns [{socket_1}, {socket_2}, ....]. Can refer to socket_i.id to distinguish
io.sockets.adapter.sids //Return {socket_1_id: {}, socket_2_id: {}} . Looks similar to the first one but the object is not actually the socket, just the information.
// Not directly helps but still relevant
io.sockets.adapter.rooms //Returns {room_1_id: {}, room_2_id: {}}
io.sockets.server.eio.clients //Return client sockets
io.sockets.server.eio.clientsCount //Return number of connected clients
Also, do note that when using socket.io with namespace, the above methods will break since io.sockets becomes an array instead of an object. To resolve, just replace io.sockets by io (i.e io.sockets.connected becomes io.connected, io.sockets.adapter.rooms becomes io.adapter.rooms ...)
另外,请注意,当使用带有命名空间的 socket.io 时,上述方法将中断,因为 io.sockets 变成了一个数组而不是一个对象。要解决,只需将 io.sockets 替换为 io(即 io.sockets.connected 变为 io.connected,io.sockets.adapter.rooms 变为 io.adapter.rooms ...)
Tested on socket.io 1.3.5
在 socket.io 1.3.5 上测试
回答by sunil n jose
I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,
我想我们可以从服务器访问socket对象,你可以分配昵称,并指向它的socket id,
io.sockets.on('connection',function(socket){
io.sockets.sockets['nickname'] = socket.id;
client.on("chat", function(data) {
var sock_id = io.sockets.sockets['nickname']
io.sockets.sockets[sock_id].emit("private", "message");
});
});
On disconnectplease remove the nickname from io.sockets.sockets.
在disconnect请从删除昵称io.sockets.sockets。
回答by John Galt
Version +2.0
版本+2.0
In version +2.0 you specify the namespace/room/node you are querying against.
在 +2.0 版本中,您指定要查询的命名空间/房间/节点。
As with broadcasting, the default is all clients from the default namespace ('/'):
与广播一样,默认是来自默认命名空间 ('/') 的所有客户端:
const io = require('socket.io')();
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
Gets a list of client IDs connected to specific namespace (across all nodes if applicable).
获取连接到特定命名空间的客户端 ID 列表(如果适用,跨所有节点)。
const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
An example to get all clients in namespace's room:
获取命名空间房间中所有客户端的示例:
const io = require('socket.io')();
io.of('/chat').in('general').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
This is from the official documentation: Socket.IO Server-API
这是来自官方文档:Socket.IO Server-API
回答by ksloan
This is the best way to access it in socket.io 1.3
这是在 socket.io 1.3 中访问它的最佳方式
Object.keys(socket.adapter.rooms[room_id])
Object.keys(socket.adapter.rooms[room_id])
回答by crickeys
For anyone that just wants a COUNT of the connected clients I believe this will do it:
对于只想要 COUNT 个连接客户端的任何人,我相信这会做到:
io.sockets.manager.server.connections
io.sockets.manager.server.connections

![在 node.js 中使用 net.createConnection(port, [host]) 创建一个 tcp 套接字](/res/img/loading.gif)