带有WebSocketServer的nodejs检查哪个客户端已关闭连接

时间:2014-03-22 21:44:01

标签: node.js

我让WebSocketServer监听连接客户端。不幸的是,我找不到检查哪个客户端已关闭连接的方法。

在     ws.on('close',function(){}); 如何查看属于哪个用户?

var WebSocketServer = require('ws').Server , wss = new WebSocketServer({port: 8080});

var playersConnected=[];
var playersConnectedByID=[];
var playersConnectedBySock=[];


wss.on('connection', function(ws) {
console.log("somebody connected");
playerID=Math.floor(Math.random() * (100000000 - 0+1) + 0);
playerID=playerID.toString();
ws.send("newID="+playerID);


//inserting new player into the right place
l=playersConnected.length; console.log("Current array length is "+l);
playersConnected[l]=([playerID,ws,"free"]);

l=playersConnected.length;
for(i=0;i<l;i++) console.log(i+" "+playersConnected[i][0]);

console.log("=================================================");

ws.on('close',function(){console.log("closing ");});

ws.on('message', function(message) { 
console.log('%s send received mess %s',playerID,message);

}
);
});
process.on('uncaughtException', function (err) {
console.log("bad connect");
console.log(err);
}); 

1 个答案:

答案 0 :(得分:0)

每个函数都形成一个局部变量的闭包,所以你可以使用一个包含所有必要信息的对象:

wss.on('connection', function(ws) {
    var playerID = Math.floor(Math.random() * (100000000 - 0+1) + 0);
    playerID = playerID.toString();
    var connection = {
        socket: ws,
        playerID: playerID
    };
    console.log("connected",connection);

    // add your other code here

    ws.on('close',function(){
        console.log("closing ", connection);
        // you will probably change this to remove_from_userlist() or similar
    });
});