zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Thinkphp5 对接百度云对象存储 BOS (上传、删除)
    php 删除富文本编辑器保存内容中的其他代码(保留中文)
    ffmreg thinkphp 控制器 获取音频视频详细信息(获取时长)
    selenium+testng+java+poi进行excel的数据参数化
    linux中磁盘配额管理
    linux中挂载和卸载文件系统
    linux中vi编辑器的练习
    Linux基础命令
    Nginx流量复制
    Python脚本
  • 原文地址:https://www.cnblogs.com/lightsong/p/10428777.html
Copyright © 2011-2022 走看看