【发布时间】:2012-02-14 06:15:45
【问题描述】:
我正在尝试使用 Socket.IO 的授权功能来获取会话数据。问题是即使我注销并销毁我的会话,Socket.IO 仍然有旧的会话信息,这显然不理想。任何想法我在下面的代码中做错了什么?
io.set('authorization', function (data, accept) {
if(data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
app.set('mongo-store').get(data.sessionID, function (err, session) {
console.log(err, session);
if (err || !session) {
// if we cannot grab a session, turn down the connection
accept('Error', false);
} else {
// save the session data and accept the connection
data.session = session;
accept(null, true);
}
});
} else {
return accept('No cookie transmitted.', false);
}
accept(null, true);
});
这里是连接代码:
io.sockets.on('connection', function(socket) {
var hs = socket.handshake;
console.log('A socket with sessionID ' + hs.sessionID
+ ' connected!');
// setup an inteval that will keep our session fresh
var intervalID = setInterval(function () {
// reload the session (just in case something changed,
// we don't want to override anything, but the age)
// reloading will also ensure we keep an up2date copy
// of the session with our connection.
hs.session.reload( function () {
// "touch" it (resetting maxAge and lastAccess)
// and save it back again.
hs.session.touch().save();
});
}, 60 * 1000);
socket.on('disconnect', function () {
console.log('A socket with sessionID ' + hs.sessionID
+ ' disconnected!');
// clear the socket interval to stop refreshing the session
clearInterval(intervalID);
});
});
【问题讨论】:
-
+1 我遇到了同样的问题。即使客户端的会话 cookie 过期或被删除,Socket.IO 连接仍然可以访问旧数据并认为会话仍然处于活动状态。
标签: javascript node.js express socket.io