Question

I use node.js and express, socket.io. I use session in Express.

How can I read the session and work with him in socket.io - in the part with connection?

store.userid is undefined.

var express = require('express')
  , stylus = require('stylus')
  , nib = require('nib')
  , sio = require('socket.io')
  , ejs = require('ejs');

store  = new express.session.MemoryStore;

app.configure(function () {

  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'secret', store: store }))

  app.use(stylus.middleware({ src: __dirname + '/public', compile: compile }))
  app.use(express.static(__dirname + '/public'));
  app.set('views', __dirname);
  app.set('view engine', 'ejs');

  //disable layout
  app.set("view options", {layout: false});
  });

app.get('/', function(req, res) {

req.session.userid = Math.floor(Math.random()*5000);

});


var io = sio.listen(app)
  , nicknames = {};
io.configure(function () {
  io.set('transports', ['websocket','flashsocket','xhr-polling']);
});


io.sockets.on('connection', function (socket) {

  socket.emit('hello', { hello: store.userid }); //store.userid is undefined

  });

In variable store:

store =

{ sessions: { 'DNHIsZqgk53zbK3xg8qescJK.dUbdgfVq0D70UaLTMGTzO4yx5vVJral2zIhVsfFGnBA': '{"lastAccess":1326317111111,"cookie":{"originalMaxAge":14399999,"expires":"2012-01-12T01:28:17.266Z",
"httpOnly":true,"path":"/"},"userid":3528}' },
  hash: [Function],
  generate: [Function] }
Was it helpful?

Solution

I could be wrong, but I don't think you can (or should) rely on the http session to be populated when you run your connection event handler. They are likely running on different protocols, and the http session relies on the browser cookie (which socket.io might send when it's doing the xhr polling, but probably won't if it's using a 'real' socket).

I would recommend having your client JS fetch the cookie (or at least the session id) manually somehow (either by fetching the cookies using JS or if you want to write it onto the page somehow... your choice). Then, when the client makes the connection, they can pass that value up and you can use it to associate it with the session. There's some docs on doing stuff that lasts all session on the github page; do a search for "session" here: https://github.com/learnboost/socket.io

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top