socket.io:clientsCount以及连接和断开连接事件

时间:2017-12-27 05:46:51

标签: node.js websocket socket.io

我通过onConnection和onDisconnect事件计算在线websockets的数量:

<DOCTYPE! html>
<html>
    <head>
        <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    </head>
    <body>
        <div id="container"></div>
        <script type='text/jsx'>
        ReactDOM.render(
            <h1>Hello World!</h1>,
            document.getElementById('container')
        );
        </script>
    </body>
</html>

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值之间的差异正在增长。

为什么会这样?

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

仅使用一个变量来计算连接可能更容易。在连接时递增它,并在断开时递减它。这就是我如何跟踪连接数量。然后,每次需要它时都不需要计算它。

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

以下是某些我正在做的事情的一个例子。下面的代码设置为监听连接&amp;断开并保持当前连接的计数。我应该注意到我没有使用像OP那样的命名空间,但计数部分是重要的。我还要注意,我在connCount > 0函数中使用send()。在我的应用程序中用于向所有连接的客户端广播。

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