Socket.io Connected User Count

后端 未结 12 840
有刺的猬
有刺的猬 2021-01-30 20:24

I finally got socket.io to work properly, but I have encountered a strange problem.

I am not sure if this is the best way, but I am using:

io.sockets.cli         


        
相关标签:
12条回答
  • 2021-01-30 21:10

    Connected Users count in number with socket.io version - 1.3.7

    io.on('connection', (socket) => {
        console.log(io.sockets.server.httpServer._connections);  //output in number
        // or
        console.log(io.sockets.server.engine.clientsCount);  //output in number
    });

    0 讨论(0)
  • 2021-01-30 21:13

    Why use an (implicit global) variable when you could always filter the array, that is returned by calling the clients() method.

    function filterNullValues (i) {
      return (i!=null);
    }
    io.sockets.clients().filter(filterNullValues).length;
    
    0 讨论(0)
  • 2021-01-30 21:14

    Tested using Socket.IO v2.3.0 using namespace, I found 4 locations having the clientCounts property (it's probably the same Server object each time):

    const socketio = require('socket.io');
    const io = socketio(http_server);
    
    const io_namespace = io.of('/foobar');
    
    io_namespace.on('connection', function(socket)
    {
        console.log(socket.conn.server.clientsCount);
        console.log(socket.server.engine.clientsCount);
        console.log(io.engine.clientsCount);
        console.log(io_namespace.server.engine.clientsCount);
    });
    
    0 讨论(0)
  • 2021-01-30 21:15

    There is a github issue for this. The problem is that whenever someone disconnects socket.io doesn't delete ( splice ) from the array, but simply sets the value to "null", so in fact you have a lot of null values in your array, which make your clients().length bigger than the connections you have in reality.

    You have to manage a different way for counting your clients, e.g. something like

    socket.on('connect', function() { connectCounter++; });
    socket.on('disconnect', function() { connectCounter--; });
    

    It's a mind buzz, why the people behind socket.io have left the things like that, but it is better explain in the github issue, which I posted as a link!

    0 讨论(0)
  • 2021-01-30 21:20

    with socket.io 2.2.0 it's easier :

    io.on('connection', function (socket) {
        console.log( socket.client.conn.server.clientsCount + " users connected" );
    });
    

    cheers

    0 讨论(0)
  • 2021-01-30 21:24

    Also take a look into:

    io.sockets.manager.connected

    It's a clean list of key value pairs (socket id and connection state?)

    0 讨论(0)
提交回复
热议问题