如何找到与我的会话连接的套接字?我在我的 node.js 服务器端 js 上的“授权”事件中获得了会话。现在我想在我的“注销”请求中断开套接字,但这对我不起作用。这是我的代码。
var express = require('express'),
redis = require('redis'),
RedisStore = require('connect-redis')(express),
store = new RedisStore({ host: '127.0.0.1', port: 6379 }),
parseCookie = express.cookieParser(secretkey);
var app = express();
var server = require("http").createServer(app),
io = require("socket.io").listen(server, { log: false }),
app.use(express.cookieParser());
app.use(express.session({ secret: secretkey, key: 'express.sid', store: store, cookie: { maxAge: 3600000 } }));
app.use(express.methodOverride());
io.set('authorization', function (handshakeData, callback) {
if (handshakeData.headers.cookie) {
parseCookie(handshakeData, null, function(err) {
handshakeData.sessionID = handshakeData.signedCookies['express.sid'];
//or if you don't have signed cookies
//handshakeData.sessionID = handshakeData.cookies['express.sid'];
console.log('manish in parseCookie 2 ' + handshakeData.sessionID + ', ' + ioClient);
store.get(handshakeData.sessionID, function (err, session) {
console.log('getting result ' + err + ', ' + session);
if (err || !session) {
// if we cannot grab a session, turn down the connection
callback('Session not found.', false);
} else {
//console.log('getting connection ' + session);
// save the session data and accept the connection
handshakeData.session = session;
callback(null, true);
}
});
});
} else {
return callback('No cookie transmitted.', false);
}
//callback(null, true);
});
io.sockets.on('connection', function(socket) {
console.log('A socket with sessionID ' + socket.handshake.sessionID + ' connected!');
socket.on('disconnect', function() {
console.log('socket.on.disconnect ' + socket.handshake.sessionID);
});
socket.on('error', function(err) {
if(err === 'handshake error') {
console.log('handshake error', err);
} else {
console.log('io error', err);
}
});
socket.on('message', function(data) {
console.log('messege received on server is "' + data + '"');
});
});
现在,当用户单击注销时,我想从该方法断开套接字;
app.post('/logout', function (req, res) {
try {
//here is my database logic
//And here I want to disconnect socket,
io.sockets.socket(req.session.id).disconnect();
}
catch (err) { nodeUtil.errorLog2(res, 'trycatch', 6, err, 'app.js', 'logout'); }
});
这不会触发任何错误,也不会进入 socket.on("disconnected") 事件。那么我该怎么做呢?