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

后端 未结 6 1060
轮回少年
轮回少年 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:34

    The solution is surprisingly simple. It's just not very well documented. It is possible to use the express session middleware as a Socket.IO middleware too with a small adapter like this:

    sio.use(function(socket, next) {
        sessionMiddleware(socket.request, socket.request.res, next);
    });
    

    Here's a full example with express 4.x, Socket.IO 1.x and Redis:

    var express = require("express");
    var Server = require("http").Server;
    var session = require("express-session");
    var RedisStore = require("connect-redis")(session);
    
    var app = express();
    var server = Server(app);
    var sio = require("socket.io")(server);
    
    var sessionMiddleware = session({
        store: new RedisStore({}), // XXX redis server config
        secret: "keyboard cat",
    });
    
    sio.use(function(socket, next) {
        sessionMiddleware(socket.request, socket.request.res || {}, next);
    });
    
    app.use(sessionMiddleware);
    
    app.get("/", function(req, res){
        req.session // Session object in a normal request
    });
    
    sio.sockets.on("connection", function(socket) {
      socket.request.session // Now it's available from Socket.IO sockets too! Win!
    });
    
    
    server.listen(8080);
    

提交回复
热议问题