1

我一直在实现套接字概念,如https://github.com/techpines/express.io/tree/master/examples/sessions,我能够显示页面初始化后存储的会话数据。但是,尽管如此,当会话数据在一段时间内不断变化时,我得到的会话数据未定义。

但是使用 socket.io 授权和握手会话可以很好地完成类似的概念,提供链接http://www.danielbaulig.de/socket-ioexpress/

客户端代码:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();

  // Emit ready event.
  setInterval(function(){
    socket.emit('ready', 'test');
  },2000);

  // Listen for get-feelings event.
  socket.on('get-feelings', function () {
  socket.emit('send-feelings', 'Good');
  })

  // Listen for session event.
  socket.on('session', function(data) {
  document.getElementById('count').value = data.count;
  })
</script>

<input type="text" id="count" />

服务器端代码:

express = require('express.io')
app = express().http().io()

// Setup your sessions, just like normal.
app.use(express.cookieParser())
app.use(express.session({secret: 'monkey'}))

// Session is automatically setup on initial request.
app.get('/', function(req, res) {
    var i = 0;
setInterval(function(){
   req.session.count = i++;
   console.log('Count Incremented as '+ req.session.count);
},1000);

res.sendfile(__dirname + '/client.html')
})

// Setup a route for the ready event, and add session data.
app.io.route('ready', function(req) {

 req.session.reload( function () {
        // "touch" it (resetting maxAge and lastAccess)
        // and save it back again.
        req.session.touch().save(function() {
           req.io.emit('get-feelings')
        });
    });
 /*
req.session.save(function() {
    req.io.emit('get-feelings')
})*/
})

// Send back the session data.
app.io.route('send-feelings', function(req) {
 console.log('Count Emitted as '+ req.session.count); // it is undefined in console

 req.session.reload( function () {
        // "touch" it (resetting maxAge and lastAccess)
        // and save it back again.
        req.session.save(function() {
          req.io.emit('session', req.session)
      });
    });

})

app.listen(7076);

在控制台中,它在每次发出时都打印为未定义...我想知道为什么套接字会话没有更新,因为原始用户会话不断变化...???

我是否需要在服务器端添加任何额外的配置来处理更改的会话数据???

4

0 回答 0