一尘不染

如何获取Websocket连接的(Express)会话ID

node.js

我在npm install ws与Express运行相同的端口上使用WebSockets 。

我想从刚刚建立并升级到WebSocket的HTTP连接中获取关联的“ sessionID”。

// start express listening
server.listen(conf.server.port, conf.server.host);

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({server: server});

wss.on('connection', function(ws) {
    var sessionID = // how do I get this?
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    ws.send('something');
});

如何才能做到这一点?

(我目前通过在页面中发送sessionID解决此问题,但这很丑陋。)


阅读 765

收藏
2020-07-07

共1个答案

一尘不染

  1. 解析Cookie
  2. 获取会话ID
  3. 获取会话数据
        var express = require('express');
    var parseCookie = express.cookieParser();
    var MemoryStore = express.session.MemoryStore;

    var store = new MemoryStore();

    app.configure(function() {
        app.use(express.session({ store: store, secret: '123456', key: 'sid' }));
    });

    wss.on('connection', function(ws) {
        parseCookie(ws.upgradeReq, null, function(err) {
            var sessionID = ws.upgradeReq.cookies['sid'];
            store.get(sessionID, function(err, session) {
                // session
            });
        }); 

        ws.on('message', function(message) {
            console.log('received: %s', message);
        });
        ws.send('something');
    });
2020-07-07