Sessions和socket.io(node.js,express.js)

时间:2022-09-22 19:43:14

How to get user session with socket.io?

如何使用socket.io获取用户会话?

io.sockets.on('connection', function(socket) {
    // Need to get user session
});

1 个解决方案

#1


1  

You can attach session with socket and get in connection event. Get the user session in authorization, if you're using express then do this:

您可以使用套接字附加会话并进入连接事件。获取授权用户会话,如果您使用快递,请执行以下操作:

var sessionStore = new express.session.MemoryStore();
io.set('authorization', function (handshake, accept){
  var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie);
  var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET');
  sessionStore.get(parsed.sid, function (error, session){
    if (session != null && session.user != null){
    accept(null, true);
    handshake.session = session;
    }
  });
});

And in your connection event you can get it like:

在你的连接事件中你可以得到它:

socket.handshake.session

#1


1  

You can attach session with socket and get in connection event. Get the user session in authorization, if you're using express then do this:

您可以使用套接字附加会话并进入连接事件。获取授权用户会话,如果您使用快递,请执行以下操作:

var sessionStore = new express.session.MemoryStore();
io.set('authorization', function (handshake, accept){
  var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie);
  var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET');
  sessionStore.get(parsed.sid, function (error, session){
    if (session != null && session.user != null){
    accept(null, true);
    handshake.session = session;
    }
  });
});

And in your connection event you can get it like:

在你的连接事件中你可以得到它:

socket.handshake.session