Accessing/Manipulating Session Data in Socket.IO (Express + Sessions + Socket.IO)
var express = require('express'); | |
var RedisStore = require('connect-redis')(express); | |
express.socketio = require('socket.io'); | |
var app = express.createServer(); | |
app.configure(function() { | |
app.use(express.cookieParser() ); | |
app.sessionStore = new express.session.MemoryStore(); //Not recommended for production use | |
app.use(express.session({ | |
'key': 'express.sid', | |
'store': app.sessionStore, | |
'cookie': {'path': '/', 'httpOnly': true, maxAge: 60 * 60 * 1000}, | |
'secret': 'foo' + Math.random() | |
}) ); | |
app.use(app.router); | |
app.use(express.static(__dirname + '/../public') ); | |
app.use(express.errorHandler() ); | |
app.set('views', __dirname + '/../views'); | |
app.set('view engine', 'jade'); | |
}); | |
//Routes | |
app.get("*", function(req, res) { | |
res.send(404); | |
}); | |
//Socket.IO Connections | |
var io = app.socketio = express.socketio.listen(app); | |
io.set('authorization', function(handshake, cb) { | |
if(handshake.headers.cookie) | |
{ | |
handshake.cookie = connect.utils.parseCookie(handshake.headers.cookie); | |
if(handshake.cookie['express.sid']) | |
{ | |
handshake.sessionID = handshake.cookie['express.sid']; | |
handshake.sessionStore = app.sessionStore; //Session contstructor needs an Object with sessionStore set | |
app.sessionStore.get(handshake.sessionID, function(err, session) { | |
if(err) | |
cb(err.message, false); | |
else | |
{ | |
var s = handshake.session = new express.session.Session(handshake, session); | |
cb(null, true); | |
} | |
}); | |
} | |
else cb('Session cookie could not be found', false); | |
} | |
else cb('Session cookie could not be found', false); | |
}); | |
io.sockets.on('connection', function(socket) { | |
console.log('Socket connected with SID: ' + socket.handshake.sessionID); | |
//Awesome! socket.handshake.session is the Session!!!! | |
socket.on('disconnect', function() { | |
console.log("DISCONNECT"); | |
}); | |
}); | |
var port = process.env.PORT || 6633; | |
app.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Many thanks to Daniel Baulig!!!
http://www.danielbaulig.de/socket-ioexpress/