使用Socket.IO,如何找出断开连接的用户的会话ID?

Tho*_*rds 3 websocket node.js socket.io

当用户断开与服务器的连接时,如何找到会话ID?

目前,我有一种丑陋的方法,要求所有现有客户发回消息.

例如在服务器上:

socket.on('disconnect', function() {
    // What’s the sessionid?
});
Run Code Online (Sandbox Code Playgroud)

rez*_*ner 8

连接时,您可以将任何数据附加到套接字:

var clients = {}
var client_id = 0;

io.sockets.on('connection', function (socket) {
  socket.client_id = client_id; // or your `session_id`
  socket.anyData = "foobar";
  clients[client_id] = socket;
  client_id++;

  socket.on("disconnect", function() {
    console.log(this.anyData) // prints: foobar
    delete clients[this.client_id];
  }
}
Run Code Online (Sandbox Code Playgroud)