本文介绍了如何获取(Express)的sessionID用于websocket连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Express Express运行的同一个端口上使用WebSockets npm install ws
d喜欢从刚刚完成并升级到WebSocket的HTTP连接中提取相关联的sessionID。
/ start express listen
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 = //如何获取这个?
ws.on('message',function消息){
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 ');
});
I'm using WebSockets npm install ws
on the same port as Express is running.
I'd like to pick up the associated 'sessionID' from the HTTP connection which had just been made and upgraded to a WebSocket.
// 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');
});
How can this be done?
(I currently work around the issue by sending the sessionID in the page, but this is ugly.)
解决方案
- Parse cookie
- Get session id
Get session data
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'); });
这篇关于如何获取(Express)的sessionID用于websocket连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!