简体   繁体   English

如何获得 socket.io 房间内的客户数量?

[英]how to get socket.io number of clients in room?

my socket.io version 1.3.5我的 socket.io 版本 1.3.5

I want to get number of clients in particular room.我想获得特定房间的客户数量。

This is my code.这是我的代码。

 socket.on('create or join', function (numClients, room) {
            socket.join(room);
    });

I use this code for get clients in room:我使用此代码让客户进入房间:

console.log('Number of clients',io.sockets.clients(room));

这适用于版本 3

io.sockets.adapter.rooms.get(roomName).size

To get the number of clients in a room you can do the following:要获取房间中的客户数量,您可以执行以下操作:

    function NumClientsInRoom(namespace, room) {
      var clients = io.nsps[namespace].adapter.rooms[room];
      return Object.keys(clients).length;
    }

This variable clients will hold a object where each client is a key.这个变量 clients 将保存一个对象,其中每个客户端都是一个键。 Then you just get the number of clients (keys) in that object.然后,您只需获取该对象中的客户端(键)数量。

If you haven't defined a namespace the default one is "/".如果您尚未定义命名空间,则默认命名空间为“/”。

Have a counter variable to keep count, increase when someone joins and decrease when people disconnect.有一个计数器变量来保持计数,当有人加入时增加,当人们断开连接时减少。

io.on('connection', function (socket) {

var numClients = {};

socket.on('join', function (room) {
    socket.join(room);
    socket.room = room;
    if (numClients[room] == undefined) {
        numClients[room] = 1;
    } else {
        numClients[room]++;
    }
});

socket.on('disconnect', function () {
     numClients[socket.room]--;
});

This work for me.这对我有用。

// check if your room isn't undefined.
if (io.sockets.adapter.rooms['your room name']) 
{
   // result
   console.log(io.sockets.adapter.rooms['your room name'].length);
}

this work for me这对我有用

io.in('yourRoom').allSockets().then(result=>{
    console.log(res.size) })

In socket.io ^1.4.6在 socket.io ^1.4.6

function numClientsInRoom(namespace, room) {
    var clients = io.nsps[namespace].adapter.rooms[room].sockets;
    return Object.keys(clients).length;
}

You need to add .sockets to rooms[room] , because variable clients holds all connection inside sockets variable.您需要将.sockets添加到rooms[room] ,因为变量 clients 将所有连接保存在sockets变量中。

我参加聚会有点晚了,但我找到了一个有效的解决方案:

io.in('YOUR_ROOM').engine.clientsCount;

socket.io's rooms is a Map whose elements map to Set s. socket.io 的rooms是一个Map ,其元素映射到Set s。

You use get(roomId) to get the value of that roomId in a Map and you use .size to the number of elements in a set unlike .length for number of elements in an array.您使用get(roomId)Map中获取该roomId的值,并使用.size来表示集合中的元素数,这与.length表示数组中的元素数不同。

 socket.on("join-room",roomId => { const room = io.of("/yourNameSpace").adapter.rooms.get(roomId) if(room === undefined || room.size < 2) { socket.join(roomId) }else { io.of("/yourNameSpace").emit("can't join link") } })

io.nsps['/'].adapter.rooms['your room name'].sockets;

如果您的命名空间不是/ ,请更改它。

Only one that worked for me in 2022 using socket.io 4.5.1: 2022 年只有一个使用 socket.io 4.5.1 对我有用:

io._nsps.get('/').adapter.rooms.get('your-room-id').size;

Thanks to @Abhishek Kumar, just making a top level comment for visibility.感谢@Abhishek Kumar,只是为了提高知名度而发表了顶级评论。

Without Adapter不带适配器

If you only have one server instance, the easiest way is:如果您只有一个服务器实例,最简单的方法是:

// rooms is a Map object
const rooms = io.of("/").adapter.rooms;
const roomSockets = rooms.get('roomid')

You can see from the official document here你可以从这里的官方文档中看到

Using An Adapter (Redis)使用适配器 (Redis)

But if you have multiple server instance and are using Adapters like Redis, this will not work as it will only returns the socket in that instance memory, so based on which server instance you request hit, the result will vary.但是,如果您有多个服务器实例并且正在使用 Redis 之类的适配器,这将不起作用,因为它只会返回该实例内存中的套接字,因此根据您请求命中的服务器实例,结果会有所不同。

To get the actual rooms and sockets, you will need to (for RedisAdapter):要获得实际的房间和插座,您需要(对于 RedisAdapter):

// this is a Set of room ids
const rooms = await io.of("/").adapter.allRooms();
// or get the sockets directly if you know the room id
const roomSockets = await io.of("/").adapter.sockets(new Set(['room id']);

You can see more methods here您可以在此处查看更多方法

Latest Documentation (v4)最新文档 (v4)

// return all Socket instances in the "room1" room of the main namespace // 返回主命名空间的“room1”房间中的所有 Socket 实例

const sockets = await io.in("room1").fetchSockets(); const sockets = 等待 io.in("room1").fetchSockets();

try sockets.size or sockets.length to get the actual count尝试 sockets.size 或 sockets.length 以获取实际计数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM