是否有可能知道哪个用户在websocket节点js中断开连接?

时间:2017-11-19 09:57:12

标签: javascript node.js websocket

我想知道哪个用户断开了websocket节点js,如果用户与服务器断开连接,但是我知道谁断开连接,我设法显示一条消息。这是我的简单代码

var server = require('ws').Server;
var s = new server({ port:5001 });
s.on('connection',function(ws){
    ws.on('message',function(message){
        console.log("Receive : "+ message);
        ws.send(message);
    });
    ws.on('close',function(){
        console.log("i lose a client");
    });
    console.log("1 more client connected");
});

1 个答案:

答案 0 :(得分:0)

套接字( ws )有一个id:

s.on('connection',function(ws){
    ws.on('message',function(message){
       console.log("Receive : " + message + " from " + ws.id);
       ws.send(message);
    });
    ws.on('close',function(){
        console.log("i lose client" + ws.id);
    });
    console.log(ws.id + " connected");
});