express session 和 socketio session关联
Posted lightsong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了express session 和 socketio session关联相关的知识,希望对你有一定的参考价值。
express session
http是没有状态的协议, 需要web框架自己实现会话和会话管理工作。
express框架有session插件可以使用。
见如下介绍:
https://www.tutorialspoint.com/expressjs/expressjs_sessions.htm
We will need the Express-session, so install it using the following code.
npm install --save express-sessionWe will put the session and cookie-parser middleware in place. In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object.
使用 session 和 cookie-parser中间件可以实现, 在req对象上回关联session对象。
var express = require(‘express‘); var cookieParser = require(‘cookie-parser‘); var session = require(‘express-session‘); var app = express(); app.use(cookieParser()); app.use(session({secret: "Shh, its a secret!"})); app.get(‘/‘, function(req, res){ if(req.session.page_views){ req.session.page_views++; res.send("You visited this page " + req.session.page_views + " times"); } else { req.session.page_views = 1; res.send("Welcome to this page for the first time!"); } }); app.listen(3000);
socketio connection session
socketio对于现在实时数据推送非常友好, 在很多网站上被使用。
如何在socketio connection上关联上对应的session, 此session为 express session创建, express创建后, 在处理的handler中, 入参数 req.session 可以获取会话。
在socketio连接上如何获取会话呢?
解决方案见下面链接:
https://github.com/wcamarao/session.socket.io/blob/master/example/server.js
ar http = require(‘http‘) , path = require(‘path‘) , connect = require(‘connect‘) , express = require(‘express‘) , app = express(); var cookieParser = express.cookieParser(‘your secret sauce‘) , sessionStore = new connect.middleware.session.MemoryStore(); app.configure(function () { app.set(‘views‘, path.resolve(‘views‘)); app.set(‘view engine‘, ‘jade‘); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(cookieParser); app.use(express.session({ secret: ‘your secret sauce‘, store: sessionStore })); app.use(app.router); }); var server = http.createServer(app) , io = require(‘socket.io‘).listen(server); var SessionSockets = require(‘session.socket.io‘) , sessionSockets = new SessionSockets(io, sessionStore, cookieParser); app.get(‘/‘, function(req, res) { req.session.foo = req.session.foo || ‘bar‘; res.render(‘index‘); }); sessionSockets.on(‘connection‘, function (err, socket, session) { socket.emit(‘session‘, session); socket.on(‘foo‘, function(value) { session.foo = value; session.save(); socket.emit(‘session‘, session); }); }); server.listen(3000);
express登录例子:
https://cnodejs.org/topic/516517a56d38277306c614da
以上是关于express session 和 socketio session关联的主要内容,如果未能解决你的问题,请参考以下文章
express session 和 socketio session关联
Express-session 和 express-socket.io-session 在 angular2 / typescript 环境中不起作用