Socket.io Connected User Count

后端 未结 12 989
有刺的猬
有刺的猬 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: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!

提交回复
热议问题