我聊天,我需要管理独特的连接.我四处搜索,但我发现的解决方案似乎都被弃用了.
那么,我如何使用Socket.IO获得套接字的会话ID?
我正在使用Node.js,Express.js和Socket.IO.
解决方法
使用Socket.IO身份验证设置,并将Cookie传递给Express的cookie解析器中间件.解析cookie后,您可以获取客户端的会话ID,并从会话存储中获取关联的会话,无论是内存故事还是其他类型的存储.
// we need to use the same secret for Socket.IO and Express var parseCookie = express.cookieParser(secret); var store = /* your MemoryStore,RedisStore,etc */; io.set('authorization',function(handshake,callback) { if (handshake.headers.cookie) { // pass a req,res,and next as if it were middleware parseCookie(handshake,null,function(err) { handshake.sessionID = handshake.signedCookies['connect.sid']; // or if you don't have signed cookies handshake.sessionID = handshake.cookies['connect.sid']; store.get(handshake.sessionID,function (err,session) { if (err || !session) { // if we cannot grab a session,turn down the connection callback('Session not found.',false); } else { // save the session data and accept the connection handshake.session = session; callback(null,true); } }); }); } else { return callback('No session.',false); } callback(null,true); });
每次客户端尝试连接时,都会运行授权功能.它需要握手头cookie(handshake.headers.cookies),并将它们传递给express.cookieParser().然后,cookie解析器找到会话ID,然后在商店中搜索关联的会话.然后,我们将关联的会话存储到handshake.session中,因此我们可以像这样访问它:
app.get('/',function(req,res) { req.session.property = 'a value'; }); io.sockets.on('connection',function(socket) { var session = socket.handshake.session; session.property // a value });