ExpressJS &Websocket &会话共享 [英] ExpressJS & Websocket & session sharing

查看:25
本文介绍了ExpressJS &Websocket &会话共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作基于 Node.js 的聊天应用程序.我想强制 websocket 服务器(ws 库)使用 ExpressJS 会话系统.不幸的是,我被卡住了.用于获取会话数据的 MemoryStore 哈希与 cookie 中的会话 ID 不同.有人能解释一下我做错了什么吗?

I'm trying to make a chat application based on Node.js. I'd like to force websocket server (ws library) to using ExpressJS session system. Unfortunately, I've got stuck. MemoryStore hashes used to get sessions' data are different than session IDs in cookies. Could somebody explain me what I'm doing wrong?

Websocket 服务器代码部分:

Websocket server code part:

module.exports = function(server, clients, express, store) {
  server.on('connection', function(websocket) {
    var username;

    function broadcast(msg, from) {...}

    function handleMessage(msg) {...}

    express.cookieParser()(websocket.upgradeReq, null, function(err) {
        var sessionID = websocket.upgradeReq.cookies['sid'];

            //I see same value in Firebug
        console.log(sessionID);

            //Shows all hashes in store
            //They're shorter than sessionID! Why?
        for(var i in store.sessions)
            console.log(i);

        store.get(sessionID, function(err, session) {
                websocket.on('message', handleMessage);

                //other code - won't be executed until sessionID in store

                websocket.on('close', function() {...});
        });
    });
});
}

存储对象定义:

var store = new express.session.MemoryStore({
    reapInterval: 60000 * 10
});

应用配置:

app.configure(function() {
    app.use(express.static(app.get("staticPath")));
    app.use(express.bodyParser());
    app.use(express.cookieParser());

    app.use(express.session({
        store: store,
        secret: "dO_ob",
        key: "sid"
    }));
});

部分主要代码:

var app = express();
var httpServer = http.createServer(app);
var websocketServer = new websocket.Server({server: httpServer});
httpServer.listen(80);

示例调试输出:

- websocket.upgradeReq.headers.cookie "sid=s%3A64a%2F6DZ4Mab8H5Q9MTKujmcw.U8PJJIR%2BOgONY57mZ1KtSPx6XSfcn%2FQPZ%2FfkGwELkmM"
- websocket.upgradeReq.cookies["sid"] "s:64a/6DZ4Mab8H5Q9MTKujmcw.U8PJJIR+OgONY57mZ1KtSPx6XSfcn/QPZ/fkGwELkmM"
- i "64a/6DZ4Mab8H5Q9MTKujmcw"

推荐答案

我发现这对我有用.不过,不确定这是最好的方法.首先,初始化您的 express 应用程序:

I found this works for me. Not sure it's the best way to do this though. First, initialize your express application:

// whatever your express app is using here...
var session = require("express-session");
var sessionParser = session({
    store: session_store,
    cookie: {secure: true, maxAge: null, httpOnly: true}
});
app.use(sessionParser);

现在,从 WS 连接显式调用会话中间件.如果您使用 express-session 模块,中间件将自行解析 cookie.否则,您可能需要先通过 cookie 解析中间件发送它.

Now, explicitly call the session middleware from the WS connection. If you're using the express-session module, the middleware will parse the cookies by itself. Otherwise, you might need to send it through your cookie-parsing middleware first.

如果您使用的是 websocket 模块:

If you're using the websocket module:

ws.on("request", function(req){
    sessionParser(req.httpRequest, {}, function(){
        console.log(req.httpRequest.session);
        // do stuff with the session here
    });
});

如果您正在使用 ws 模块:

If you're using the ws module:

ws.on("connection", function(req){
    sessionParser(req.upgradeReq, {}, function(){
        console.log(req.upgradeReq.session);
        // do stuff with the session here
    });
});

为方便起见,这里有一个完整的示例,使用 expressexpress-sessionws:

For your convenience, here is a fully working example, using express, express-session, and ws:

var app = require('express')();
var server = require("http").createServer(app);
var sessionParser = require('express-session')({
    secret:"secret",
    resave: true,
    saveUninitialized: true
});
app.use(sessionParser);

app.get("*", function(req, res, next) {
    req.session.working = "yes!";
    res.send("<script>var ws = new WebSocket('ws://localhost:3000');</script>");
});

var ws = new require("ws").Server({server: server});
ws.on("connection", function connection(req) {
    sessionParser(req.upgradeReq, {}, function(){
        console.log("New websocket connection:");
        var sess = req.upgradeReq.session;
        console.log("working = " + sess.working);
    });
});

server.listen(3000);

这篇关于ExpressJS &amp;Websocket &amp;会话共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆