socket.io 和会话? [英] socket.io and session?

查看:26
本文介绍了socket.io 和会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用快速框架.我想从 socket.io 访问会话数据.我尝试使用 client.listener.server.dynamicViewHelpers 数据表达 dynamicHelpers,但我无法获取会话数据.有没有一种简单的方法可以做到这一点?请看代码

I'm using express framework. I want to reach session data from socket.io. I tried express dynamicHelpers with client.listener.server.dynamicViewHelpers data, but i can't get session data. Is there a simple way to do this? Please see the code

app.listen(3000);

var io = require('socket.io');
var io = io.listen(app);

io.on('connection', function(client){
    // I want to use session data here
    client.on('message', function(message){
        // or here
    });
    client.on('disconnect', function(){
        // or here
    }); 
});

推荐答案

这不适用于通过 flashsocket 传输的套接字(它不会向服务器发送所需的 cookie),但它可以可靠地用于其他一切.我只是在我的代码中禁用了 flashsocket 传输.

This won't work for sockets going over the flashsocket transport (it doesn't send the server the needed cookies) but it reliably works for everything else. I just disable the flashsocket transport in my code.

为了使其工作,在 express/connect 端,我明确定义了会话存储,以便我可以在套接字内使用它:

To make it work, in the express/connect side, I explicitly define the session store so I can use it inside socket:

MemoryStore = require('connect/middleware/session/memory'),
var session_store = new MemoryStore();
app.configure(function () {
  app.use(express.session({ store: session_store }));
});

然后在我的套接字代码中,我包含了连接框架,以便我可以使用它的 cookie 解析从 cookie 中检索 connect.sid.然后我在会话存储中查找具有 connect.sid 的会话,如下所示:

Then inside my socket code, I include the connect framework so I can use its cookie parsing to retrieve the connect.sid from the cookies. I then look up the session in the session store that has that connect.sid like so:

var connect = require('connect');
io.on('connection', function(socket_client) {
  var cookie_string = socket_client.request.headers.cookie;
  var parsed_cookies = connect.utils.parseCookie(cookie_string);
  var connect_sid = parsed_cookies['connect.sid'];
  if (connect_sid) {
    session_store.get(connect_sid, function (error, session) {
      //HOORAY NOW YOU'VE GOT THE SESSION OBJECT!!!!
    });
  }
});

然后您可以根据需要使用会话.

You can then use the session as needed.

这篇关于socket.io 和会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆