我在npm install ws与Express运行相同的端口上使用WebSockets 。
npm install ws
我想从刚刚建立并升级到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解决此问题,但这很丑陋。)
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'); });