Socket.io: How to calculate count of websockets online using callbacks of “connection” and “disconnect” events (or another events)?

怎甘沉沦 提交于 2020-01-16 12:18:17

问题


I need to get count of websockets online.

I trying to calculate this that:

const socketIo = require('socket.io');

const app = require('express')();
const http = require('http').Server(app);

var online = 0;

var port = 6001;
var io = socketIo(port);

//I have only one NameSpace and root NS is not used
var ns1 = io.of('ns1');

ns1
    .on('connection', function (socket) {
        online += 1;

        socket.on('disconnect', function (reason) {
            online -= 1;
        });
    });

...

app.get('/', function (req, res) {
    res.send({
        clientsCount: io.engine.clientsCount,
        online: online
    });
});

http.listen(8000, function () {
    console.log('Web app is listening');
});

I have a problem: why "online" not equal "clientsCount"?

What is right way to calculate count of websockets online using events callbacks?


回答1:


make sure your client connect to the same namespace, something like the following code:

io('http://localhost:6001/ns1'); // client connection


来源:https://stackoverflow.com/questions/48375213/socket-io-how-to-calculate-count-of-websockets-online-using-callbacks-of-conne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!