Sessions merge socket.io and express.js

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

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 a user moves from one URL to another, the session identifier also changes: but I do not 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 
+7
source share
1 answer

You output the socket id, not the session id from express.js.

You must use the authorization event, its first parameter is an object that has an entry called sessionID . This value should not change between page reloads, as it is stored in a cookie (or in the redis database or any other).

Here is a good article explaining how this works: http://www.danielbaulig.de/socket-ioexpress/ , but it's a bit outdated. The basic principle remains the same, but several details have changed. For example, the server creation method no longer works, and connection developers removed parseCookie() . Users are not happy with this solution, however, this easy-to-remember line of code is a workaround:

 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, 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 get it later using socket.handshake , in your case: socket.handshake.sessionID .

Hope this helps.

+6
source

All Articles