• 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-session
    

    We 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 4之上版本 express session天生支持

    https://blog.csdn.net/u012251421/article/details/76207034

    express 4.x可以直接把express-session中间件当成socket.io处理,所以可以简单像下面这样,就可以共享express的session了

    1. sio.use(function(socket, next) {
    2. sessionMiddleware(socket.request, socket.request.res, next);
    3. });

    example:

    1. var Server = require("http").Server;
    2. var session = require("express-session");
    3.  
    4. var app = express();
    5. var server = Server(app);
    6. var sio = require("socket.io")(server);
    7.  
    8. var sessionMiddleware = session({
    9. secret: "keyboard cat",
    10. resave: false,
    11. saveUninitialized: true
    12. });
    13.  
    14. sio.use(function(socket, next) {
    15. sessionMiddleware(socket.request, socket.request.res, next);
    16. });
    17.  
    18. app.use(sessionMiddleware);
    19.  
    20. app.get("/", function(req, res){
    21. req.session.username = 'jim';
    22. });
    23.  
    24. sio.sockets.on("connection", function(socket) {
    25. console.log(socket.request.session.username); // 'jim'
    26. });
    27.  
    28. server.listen(80);
    29.  

    express-socket.io-session

    https://www.npmjs.com/package/express-socket.io-session

    After every socket connection, you'll have socket.handshake.session. That is the same session object req.session you get in your route middleware when your app uses express-session.

     

    Modifying session data inside socket.io event handlers

    When inside express, you normally get to modify your session variables trusting that express-session saves them for you.

    Invoke this module with an option of autoSave:true in order for achieveing the same behaviour.

    io.use(sharedsession(session{
        autoSave:true
    }));
    var app = require('express')(),
      server  = require("http").createServer(app),
      io = require("socket.io")(server),
      session = require("express-session")({
        secret: "my-secret",
        resave: true,
        saveUninitialized: true
      }),
      sharedsession = require("express-socket.io-session");
     
     
    // Attach session
    app.use(session);
     
    // Share session with io sockets
     
    io.use(sharedsession(session));
     
    io.on("connection", function(socket) {
        // Accept a login event with user's data
        socket.on("login", function(userdata) {
            socket.handshake.session.userdata = userdata;
            socket.handshake.session.save();
        });
        socket.on("logout", function(userdata) {
            if (socket.handshake.session.userdata) {
                delete socket.handshake.session.userdata;
                socket.handshake.session.save();
            }
        });        
    });
     
    server.listen(3000);

    express登录例子:

    https://cnodejs.org/topic/516517a56d38277306c614da

  • 相关阅读:
    UVA 11174 Stand in a Line,UVA 1436 Counting heaps —— (组合数的好题)
    UVA 1393 Highways,UVA 12075 Counting Triangles —— (组合数,dp)
    【Same Tree】cpp
    【Recover Binary Search Tree】cpp
    【Binary Tree Zigzag Level Order Traversal】cpp
    【Binary Tree Level Order Traversal II 】cpp
    【Binary Tree Level Order Traversal】cpp
    【Binary Tree Post order Traversal】cpp
    【Binary Tree Inorder Traversal】cpp
    【Binary Tree Preorder Traversal】cpp
  • 原文地址:https://www.cnblogs.com/lightsong/p/10428777.html
Copyright © 2020-2023  润新知