简体   繁体   中英

merge socket.io and express.js sessions

I want to merge express.js and socket.io sessions together. Below is my code (socket.io part)

var io = require('socket.io').listen(app);
io.set('log level', 1);

io.sockets.on('connection', function (socket) {
    console.log('client connected');
client.send(client.id);//send client id to client itself
socket.on('connect', function(){
    console.log(socket.id + ' connected');
});
socket.on('disconnect', function(){
    console.log(socket.id + ' disconnected');
});
});

My express.js Session settings:

app.configure(function() {
  //app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/static'));
  app.use(express.cookieParser());
  app.use(express.session({store: MemStore({
    reapInterval: 60000 * 10
  }), secret:'foobar', key: 'express.sid'
}));

My main problem is in my terminal when user travels from one url to another, the session id changes also: But I don't want it to be changed.

info  - socket.io started
client connected
client connected
4Z0bYHzfWCEFzbbe4WUK disconnected
e_uSvxhSLbLAC9-F4WUL disconnected
client connected
bKDy90gsrWWTRJDD4WUM disconnected
client connected
RJ5qqCL2wfmXbd7U4WUN disconnected
client connected
wjN5Sqx4rucRtWL_4WUO disconnected

You are outputting the socket ID, not the session ID from express.js.

You must use the authorization event, its first parameter is an object which has an entry called sessionID . That value shouldn't change between page reloads, as it is stored in a cookie (or redis database or whatever).

Here is a good article explaining how it works: http://www.danielbaulig.de/socket-ioexpress/ , but it's a little outdated. The basic principle stays the same, but a few details have changed. For example the way he creates the server doesn't work anymore, and the connect developers have removed parseCookie() . Users are not happy with that decision, however the workaround is this easy-to-remember line of code:

connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(data.headers.cookie)), secret);

As I said, the article mentioned above should give you all the basics you need, if you want to see a working implementation, take a look at this: https://github.com/vortec/lolbr/blob/master/lib/lolbr.js

Inside the authorization event handler, you can modify the data object and access it later it using socket.handshake , in your case: socket.handshake.sessionID .

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM