Socket.io 1.0.5 : How to save session variables?

旧时模样 提交于 2020-01-04 14:11:51

问题


Unfortunately socket.io developer team decided to deprecate functions set() and get(). The problem is that these two functions allowed us to save variable into session.

So my question is : What is the equivalent of the folloing code on socket.io 1.0.5 ?

socket.set('mySessionVar', 'myValue');

socket.get('mySessionVar', function (error, mySessionVar) {
    console.log('I have a super variable save in the session : '+mySessionVar);
    socket.emit('mySessionVar', mySessionVar);
});

Thank you for your help, Guillaume.


回答1:


socket.io-handshake is session middleware for socket.io 1.x. It is built on top of express-session and cookie-parser. I know we are talking about socket.io and not express, but it still works with socket.io. This example will make your sessions live on a redis store.

var expressSession = require('express-session');
var connectRedis = require('connect-redis')(expressSession);
var cookieParser = require('cookie-parser');
var config = { session: { secret:'secret', key: 'bus.io', store: new connectRedis() } };
var handshake = require('socket.io-handshake');
var io = require('socket.io')(3000);
io.use(handshake(config.session));
io.on('connection', function (socket) {
  socket.handshake.session.data = "whatever data I want";
  socket.handshake.session.save();
});



回答2:


Your 'socket' is a Javascript object, to which you can add any additional key/values.

socket['mySessionVar'] = 'myValue';
console.log( "I have a super variable save in the session: " + socket['mySessionVar']);


来源:https://stackoverflow.com/questions/24290699/socket-io-1-0-5-how-to-save-session-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!