socket.io: disconnect event isn't fired

后端 未结 3 2030
遥遥无期
遥遥无期 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.

    0 讨论(0)
  • 2021-02-01 03:24

    Put your on disconnect code inside your on connect block and edit it a bit like so:

    io.sockets.on('connection', function (socket) {
        count++;
        io.sockets.emit('count', {
            number: count
        });
    
        socket.on('disconnect', function () {
            console.log('DISCONNESSO!!! ');
            count--;
            io.sockets.emit('count', {
                number: count
            });
        });
    });
    

    This way you're detecting when a specific socket (specifically the socket you pass to your anonymous function that is run on connection) is disconnected.

    0 讨论(0)
  • 2021-02-01 03:28

    Just in case anyone else made this silly mistake: make sure that any socket middleware you've defined calls next() at the end, or else no other socket handlers will run.

    // make sure to call next() at the end or...
    io.use(function (socket, next) {
        console.log(socket.id, "connection middleware");
        next(); // don't forget this!
    });
    
    // ...none of the following will run:
    
    io.use(function (socket, next) {
        console.log(socket.id, "second middleware");
        next(); // don't forget this either!
    });
    
    io.on("connection", function (socket) {
        console.log(socket.id, "connection event");
        socket.once("disconnect", function () {
            console.log(socket.id, "disconnected");
        });
    });
    
    0 讨论(0)
提交回复
热议问题