简体   繁体   中英

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

How to get user session with socket.io?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM