您需要从不同位置获取客户端数量:
io.sockets.clients().length
但是,当您阅读此活动 GitHub 问题时,您可能希望避免该操作,因为它可能导致额外的内存泄漏(超出套接字已经发生的情况)。
这是一个完整的工作示例:
var app = require('express')();
var server = require("http").createServer(app);
var io = require('socket.io').listen(server);
server.listen(1339);
app.get('/', function(req, res) {
return res.sendfile(__dirname + "/index.html");
});
/*
to obtain number of connected clients
io.sockets.clients().length
*/
console.log("INIT", io.sockets.clients().length );
io.sockets.on("connection", function(socket) {
console.log("CONNECT:" + io.sockets.clients().length);
socket.on("disconnect", function(data){
console.log("DISCONNECT: ", io.sockets.clients().length);
});
});
断开连接事件发生在客户端被删除之前,因此计数将比客户端总数高一(取决于您如何看待它)。
此外,on
由于某种原因,您让事件处理程序返回值,所以我删除了它。
与其使用该函数,不如使用一个简单的计数器来获得更好的运气:
var clientsConnected = 0;
console.log("INIT", io.sockets.clients().length );
io.sockets.on("connection", function(socket) {
console.log("CONNECT:" + ++clientsConnected);
socket.on("disconnect", function(data){
console.log("DISCONNECT: ", --clientsConnected);
});
});
有些人显然报告说断开连接的数量可能超过连接的数量,因此您可能希望防止计数器降至零以下。
连接了两个客户端(然后断开了一个):
info: socket.io started
INIT 0
debug: served static content /socket.io.js
debug: client authorized
info: handshake authorized eJcvVsr60fmRzhVpQ6rO
debug: setting request GET /socket.io/1/websocket/eJcvVsr60fmRzhVpQ6rO
debug: set heartbeat interval for client eJcvVsr60fmRzhVpQ6rO
debug: client authorized for
debug: websocket writing 1::
CONNECT:1
debug: served static content /socket.io.js
debug: client authorized
info: handshake authorized 28lUudTS3KtCphd0Q6rP
debug: setting request GET /socket.io/1/websocket/28lUudTS3KtCphd0Q6rP
debug: set heartbeat interval for client 28lUudTS3KtCphd0Q6rP
debug: client authorized for
debug: websocket writing 1::
CONNECT:2
info: transport end (socket end)
debug: set close timeout for client 28lUudTS3KtCphd0Q6rP
debug: cleared close timeout for client 28lUudTS3KtCphd0Q6rP
debug: cleared heartbeat interval for client 28lUudTS3KtCphd0Q6rP
DISCONNECT: 2
debug: discarding transport
info: transport end (socket end)
debug: set close timeout for client eJcvVsr60fmRzhVpQ6rO
debug: cleared close timeout for client eJcvVsr60fmRzhVpQ6rO
debug: cleared heartbeat interval for client eJcvVsr60fmRzhVpQ6rO
DISCONNECT: 1
debug: discarding transport