【问题标题】:Using Socket.IO, how can I find out the session ID of a disconnected user?使用 Socket.IO,如何找出断开连接用户的会话 ID?
【发布时间】:2012-01-28 05:05:13
【问题描述】:

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

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

例如在服务器上:

socket.on('disconnect', function() {
    // What’s the sessionid?
});

【问题讨论】:

  • 我认为我的回答不足以真正回答这个问题,所以我删除了它。但是,我认为该链接可能会有所帮助:chrissilich.com/blog/… 简而言之,一些带有 socket.id 的黑客。
  • 谢谢 - 这似乎不是很明显,所以期待一点黑客!

标签: node.js websocket socket.io


【解决方案1】:

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

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];
  }
}

【讨论】:

    【解决方案2】:
    socket.on('disconnect', function() {
        console.log(this.id);
    });
    

    将为您提供已关闭的套接字的 ID,但这可能更像是一种 hack... :)

    【讨论】:

    • 如果这是“未定义”是什么意思?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2017-07-17
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2019-08-04
    • 2017-05-08
    相关资源
    最近更新 更多