socket.io: disconnect event isn't fired

后端 未结 3 2043
遥遥无期
遥遥无期 2021-02-01 02:36

I have made a simple realtime visitor counter.

You can download it from this repository.

What happens is that disconnect event (even after browser closing) on se

3条回答
  •  独厮守ぢ
    2021-02-01 03:18

    From Socket.IO 1.0 the io.engine.clientsCount property is available. This property tells you how many open connection does your app currently have.

    io.sockets.on('connection', function (socket) {
        io.sockets.emit('count', {
            number: io.engine.clientsCount
        });
    
        socket.once('disconnect', function () {
            io.sockets.emit('count', {
                number: io.engine.clientsCount
            });
        });
    });
    

    Note: Use .once instead of .on and the listener will be removed automatically from the socket what is good for us now, because the disconnect event is only fired once per socket.

提交回复
热议问题