The number of customers in the room in the io v1 outlet

I just started playing with socket.io and tried to make something super simple, like people connecting to a room.

I expected this to give me the number of customers in the room

io.sockets.on('connection', function (socket){
    socket.on('create or join', function (channel) {
        var numClients = io.sockets.clients(channel).length;
        ...
   }
})

But it returns an error: Object #<Namespace> has no method 'clients'because something has changed in V.1. After some searches, I replaced the callback with another:

    var clients = io.sockets.adapter.rooms[channel];
    var numClients = 0;
    if (typeof clients !== 'undefined'){
        numClients = clients.length;
    }

    p(numClients);   // p is just a wrapper on console.log()
    p(clients);
    socket.join(channel);
    socket.emit('created', channel);

But no matter how many times I connect, I get 0 as the number of clients:

0
undefined
0
[ hSxLuOqrm5bX4UxmAAAA: true ]
0
[ hSxLuOqrm5bX4UxmAAAA: true, '2bjYS0lrUFySPM1OAAAB': true ]

What am I doing wrong?

PS here's how to get the number of customers in a room:

var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;

+4
source share
1 answer

, clients , (, ).

, :

var clients = [];
clients.somekey1 = true;
clients.somekey2 = true;

console.log(clients.length);
console.log(clients);

:

0
[ somekey1: true, somekey2: true ]

0, . clients , "" :

var numClients = Object.keys(clients).length;

MDN:

Object.keys() , for...in ( , for-in ).

, .

+5

Source: https://habr.com/ru/post/1545457/


All Articles