【问题标题】: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?
});
【问题讨论】:
标签:
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... :)