2013-08-26 48 views
3

我寫了一個非常簡單的腳本來檢索連接用戶列表。錯誤的連接號碼

​​

和HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>title</title> 
</head> 
<body> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
     var socket = io.connect('http://localhost:1339'); 
    </script> 
</body> 
</html> 

當我運行的應用程序,我得到0在init,但是隻要我在瀏覽器中打開網頁它給了我4連接,而不是僅僅1。另外我得到一個connections property is deprecated. Use getConnections() method警告。我使用v0.10.15中的節點和v0.9.16中的socket.io。

回答

5

你需要從不同的位置獲取客戶端的數量:

io.sockets.clients().length 

但是,當你閱讀this active GitHub issue,你可能想避免這種操作,因爲它可以造成額外的內存泄漏(除套接字已經發生了什麼)。

下面是一個完整的工作示例:(你如何看待它取決於)

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