node.js socket.io:断开连接事件未触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10342548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:36:36  来源:igfitidea点击:

socket.io: disconnect event isn't fired

node.jseventssocket.iodisconnect

提问by Giovanni Bitliner

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 server is never fired.

发生的情况是永远不会触发服务器上的断开连接事件(即使在浏览器关闭后)。

server.js is:

server.js 是:

(function () {
var app, count, express, io;

express = require('express');
io = require('socket.io');

app = module.exports = express.createServer();

app.configure(function () {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(require('stylus').middleware({
        src: __dirname + '/public'
    }));
    app.use(app.router);
    return app.use(express.static(__dirname + '/public'));
});

app.configure('development', function () {
    return app.use(express.errorHandler({
        dumpExceptions: true,
        showStack: true
    }));
});
app.configure('production', function () {
    return app.use(express.errorHandler());
});

io = require('socket.io').listen(app);

count = 0;

io.sockets.on('connection', function (socket) {
    count++;
    io.sockets.emit('count', {
        number: count
    });
});

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


app.get('/', function (req, res) {
    return res.render('index', {
        title: 'node.js express socket.io counter'
    });
});
if (!module.parent) {
    app.listen(10927);
    console.log("Express server listening on port %d", app.address().port);
}

}).call(this);

Script on the client is:

客户端的脚本是:

    script(type='text/javascript')

        var socket = io.connect();

        socket.on('count', function (data) {
            $('#count').html( data.number );
        });

回答by swiecki

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

将断开连接代码放在 on connect 块中,然后像这样编辑它:

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.

通过这种方式,您可以检测特定套接字(特别是您传递给在连接上运行的匿名函数的套接字)何时断开连接。

回答by NoNameProvided

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

从 Socket.IO 1.0 开始,io.engine.clientsCount属性可用。这个属性告诉你你的应用程序当前有多少打开的连接。

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 .onceinstead of .onand the listener will be removed automatically from the socketwhat is good for us now, because the disconnect event is only fired once per socket.

注意:使用.once而不是,.on监听器将从socket现在对我们有好处的东西中自动删除,因为每个套接字只触发一次 disconnect 事件。

回答by Galen Long

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.

以防万一其他人犯了这个愚蠢的错误:确保您定义的任何套接字中间件最后都调用next(),否则不会运行其他套接字处理程序。

// 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");
    });
});