在 socket.IO 3.x 中
3.x 版本的新功能是 connected 被重命名为 sockets,现在是命名空间上的 ES6 Map。在房间套接字上是一组 ES6 客户端 ID。
//this is an ES6 Set of all client ids in the room
const clients = io.sockets.adapter.rooms.get('Room Name');
//to get the number of clients in this room
const numClients = clients ? clients.size : 0;
//to just emit the same event to all members of a room
io.to('Room Name').emit('new event', 'Updates');
for (const clientId of clients ) {
//this is the socket of each client in the room.
const clientSocket = io.sockets.sockets.get(clientId);
//you can do whatever you need with this
clientSocket.leave('Other Room')
}
在 socket.IO 1.x 到 2.x
请参考以下答案:
获取特定房间中所有客户的列表。复制如下,并进行了一些修改:
const clients = io.sockets.adapter.rooms['Room Name'].sockets;
//to get the number of clients in this room
const numClients = clients ? Object.keys(clients).length : 0;
//to just emit the same event to all members of a room
io.to('Room Name').emit('new event', 'Updates');
for (const clientId in clients ) {
//this is the socket of each client in the room.
const clientSocket = io.sockets.connected[clientId];
//you can do whatever you need with this
clientSocket.leave('Other Room')
}