简体   繁体   中英

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

my socket.io version 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. 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

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.

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

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

socket.io's rooms is a Map whose elements map to 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.

 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:

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

Thanks to @Abhishek Kumar, just making a top level comment for visibility.

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)

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.

To get the actual rooms and sockets, you will need to (for 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)

// return all Socket instances in the "room1" room of the main namespace

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

try sockets.size or sockets.length to get the actual count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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