How to share sessions with Socket.IO 1.x and Express 4.x?

后端 未结 6 1128
轮回少年
轮回少年 2020-11-22 15:14

How can I share a session with Socket.io 1.0 and Express 4.x? I use a Redis Store, but I believe it should not matter. I know I have to use a middleware to look at cookies a

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 15:29

    Now, the original accepted answer doesn't work for me either. Same as @Rahil051, I used express-socket.io-session module, and it still works. This module uses cookie-parser, to parse session id before entering express-session middleware. I think it's silmiar to @pootzko, @Mustafa and @Kosar's answer.

    I'm using these modules:

    "dependencies": 
    {
      "debug": "^2.6.1",
      "express": "^4.14.1",
      "express-session": "^1.15.1",
      "express-socket.io-session": "^1.3.2
      "socket.io": "^1.7.3"
    }
    

    check out the data in socket.handshake:

    const debug = require('debug')('ws');
    const sharedsession = require('express-socket.io-session');
    
    module.exports = (server, session) => {
        const io = require('socket.io').listen(server);
        let connections = [];
    
        io.use(sharedsession(session, {
            autoSave: true,
        }));
    
        io.use(function (socket, next) {
            debug('check handshake %s', JSON.stringify(socket.handshake, null, 2));
            debug('check headers %s', JSON.stringify(socket.request.headers));
            debug('check socket.id %s', JSON.stringify(socket.id));
            next();
        });
    
        io.sockets.on('connection', (socket) => {
            connections.push(socket);
        });
    };
    

提交回复
热议问题