【问题标题】:socket.io: clientsCount and on connection and on disconnect eventssocket.io:clientsCount 以及连接和断开事件
【发布时间】:2018-02-01 01:55:01
【问题描述】:

我通过 onConnection 和 onDisconnect 事件统计在线 websocket 的数量:

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

var on_connect = 0;
var on_disconnect = 0;

var port = 6001;
var io = socketIo(port, {
    pingTimeout: 5000,
    pingInterval: 10000
});

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

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

        socket.on('disconnect', function (reason) {
            on_disconnect += 1;
        });
    });

...

var online = on_connect - on_disconnect;

...

但是online 值不等于io.engine.clientsCount 值。

随着时间的推移,online 值和io.engine.clientsCount 值之间的差异越来越大。

为什么会这样?

需要做什么来解决这个问题?

【问题讨论】:

标签: node.js websocket socket.io


【解决方案1】:

on_connect 和 on_disconnect 变量是回调事件中的更新,而 online 变量不会重新计算。因此,每次其他变量发生变化时,您都需要重新计算在线变量。

【讨论】:

  • 没有。这不是生产代码。这是代码示例。
【解决方案2】:

只使用一个变量来计算连接数可能更容易。连接时增加,断开连接时减少。这就是我跟踪连接数的方式。那么就不需要每次需要它的值时都计算它。

此外,声明var online = on_connect - on_disconnect; 正在发生之前 的行也被修改...这就是@gvmani 试图告诉你的。

这是我正在做的一些示例。下面的代码设置为侦听连接和断开连接并维护当前连接的计数。我应该注意,我没有使用像 OP 这样的命名空间,但计数部分才是重要的。我还要注意我在send() 函数中使用了connCount > 0。在我的应用程序中,它用于向所有连接的客户端广播。

/* ******************************************************************** */
// initialize the server
const http   = require('http');
const server = http.createServer();

// Socket.io listens to our server
const io = require('socket.io').listen(server);

// Count connections as they occur, decrement when a client disconnects.
// If the counter is zero then we won't send anything over the socket.
var connCount = 0;

// A client has connected, 
io.on('connection', function(socket) {

    // Increment the connection counter
    connCount += 1;

    // log the new connection for debugging purposes.
    console.log(`on connect - ${socket.id}   ${connCount}`);

    // The client that initiated the connection has disconnected.
    socket.on('disconnect', function () {
        connCount -= 1;
        console.log(`on disconnect - ${socket.id}   ${connCount}`);
    });
});

// Start listening...
server.listen(3000);

// Send something to all connected clients (a broadcast) the
// 'channel' will indicate the destination within the client
// and 'data' becomes the payload. 
function send(channel, data) {
    console.log(`send() - channel = ${channel}  payload = ${JSON.stringify(data)}`);
    if(connCount > 0) io.emit(channel, {payload: data});
    else console.log('send() - no connections');
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 2013-08-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多