express session 和 socketio session關聯
阿新 • • 發佈:2019-02-25
sessions point 實時 not func emit 參數 save times
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關聯