如何获取Websocket连接的(Express)会话ID
我在npm install ws
与Express运行相同的端口上使用WebSockets 。
我想从刚刚建立并升级到WebSocket的HTTP连接中获取关联的“ sessionID”。
// start express listeningserver.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解决此问题,但这很丑陋。)
回答:
- 解析Cookie
- 获取会话ID
- 获取会话数据
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');
});
以上是 如何获取Websocket连接的(Express)会话ID 的全部内容, 来源链接: utcz.com/qa/428239.html