Skip to content

Instantly share code, notes, and snippets.

@atian25
Created August 13, 2012 06:39
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save atian25/3337459 to your computer and use it in GitHub Desktop.
Save atian25/3337459 to your computer and use it in GitHub Desktop.
socket.io + express session
//express3.0
var express = require('express');
var app = express();
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
//session & cookie
var sessionStore = new express.session.MemoryStore({reapInterval: 60000 * 10});
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
key: 'sid',
secret: 'your_session_secret'
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("%s listening on port %d in %s mode", 'your_project_name', app.get('port'), app.settings.env);
console.log("God bless love....");
console.log("You can visit your app with http://localhost:%d", app.get('port'));
});
//通过cookie读取sessionid,进而得到session
var chatServer = io.of('/chat');
chatServer.authorization(function(handshakeData, callback) {
//没有cookie则退出
if (!handshakeData.headers.cookie) return callback('socket.io: no found cookie.', false);
//根据cookie找sessionId,https://github.com/DanielBaulig/sioe-demo/blob/master/app.js
var signedCookies = require('express/node_modules/cookie').parse(handshakeData.headers.cookie);
handshakeData.cookies = require('express/node_modules/connect/lib/utils').parseSignedCookies(signedCookies, 'your_session_secret');
//根据sessionId找username
sessionStore.get(handshakeData.cookies['sid'], function(err, session) {
if (err || !session) return callback('socket.io: no found session.', false);
//得到session存入handshakeData
handshakeData.session = session;
if (handshakeData.session.user) {
return callback(null, true);
} else {
return callback('socket.io: no found session.user', false);
}
})
});
chatServer.on('connection', function (client) {
//读取session
var username = client.handshake.session.user.username;
});
@xh3b4sd
Copy link

xh3b4sd commented Jun 28, 2013

Very cool, particularly because there is no good documentation about connecting express sessions and socket.io sessions. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment