Modificar los datos de la sesión desde dentro de la devolución de llamada de socket.io

I am currently using this stack expres, socket.io, sessionstore. I followed the article here http://www.danielbaulig.de/socket-ioexpress/. Well the problem is that i cannot modify the session values in socket.io callback.

Access from express side works well, the item get increased after each refresh.

app.get('/mysession', function(req, res) {
  req.session.item++;
  console.log(req.session);

  res.render('session.jade', {
    title: 'Sample title'
  });
});

Using in socket.io side it does not and here is the problem, maybe i am setting the wrong object.

var io = io.listen(app);
io.sockets.on('connection', function(socket) {
  var handshake = socket.handshake;
  onlineCount++;
  console.log('Well done id %s', handshake.sessionID);
  handshake.session.item++;

  console.log(handshake.session);

});

Here is bridge code.

io.set('authorization', function(data, accept) {
  if (data.headers.cookie) {
    data.cookie = parseCookie(data.headers.cookie);
    data.sessionID = data.cookie['express.sid'];
    sessionStore.get(data.sessionID, function(err, session) {
      if (err || !session) {
        accept('Error', false);
      } else {
        data.session = session;
        accept(null, true);
      }
    });
  } else {
    return accept('No cookie tansmitted', false);
  }
});

preguntado el 02 de febrero de 12 a las 10:02

2 Respuestas

The only way I found to make this work is to grab the cookie from the request object on the connect event, parse it with your favourite cookie parser (I use connect.utils.parseCookie), and set it on that socket so that I may access it in future events:

socket.on('connection', function(client) {
  var cookie = client.request.headers.cookie;
  var pcookie = connect.utils.parseCookie(cookie);
  var session_id = pcookie["connect.sid"];
  if (session_id) {
    sessionStore.get(session_id, function(err, sess) {
      // do whatever you want with sess here
      // ...
      // if you want to "save" the session for future events
      client.set('session_id', session_id);
    }
  }
});

Respondido el 02 de junio de 12 a las 19:06

La sessionStore API changed a little bit, now its sessionStore.load(sessionId, cb) en lugar de .get.

Respondido el 02 de junio de 12 a las 19:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.