Skip to content

Instantly share code, notes, and snippets.

@heygambo
Forked from flockonus/app.js
Created March 6, 2012 19:58
Show Gist options
  • Save heygambo/1988659 to your computer and use it in GitHub Desktop.
Save heygambo/1988659 to your computer and use it in GitHub Desktop.
An Express app that should integrate to socket.io
/**
* Module dependencies.
*/
var express = require('express');
var app = module.exports = express.createServer();
io = require('socket.io').listen(app),
sessionStore = new express.session.MemoryStore(),
fs = require('fs'),
C = console.log
// Configuration
app.configure(function(){
app.use(express.logger({format: 'dev'}));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'evilWorldDom1nat10nPlanzt1temzbiIitCh34sORevilWorldDom1nat10nPlanz',
key: 'express.sid',
}));
app.use(app.router);
app.use(express.static( __dirname + '/public'));
app.use(function (req, res) {
//C('<h2>Hello, your session id is', req.session, '</h2>')
});
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
/*
* Serve socket.io
*/
app.get('/', function(req, res, next){
C("/", req.headers )
if( req.session.game_id && req.session.user_id ){
res.render('index', {
title: 'Flockin - lets sock!',
game_id: req.session.game_id,
user_id: req.session.user_id,
});
} else {
res.redirect('/404.html', 404);
}
});
/*
* get a QR code, and match with DB
*/
app.get('/qrcode', function(req,res,next){
C( "New Player!", req.query )
// TODO check the BD
// mock, require ?code=asdsadsadsa
if( req.query && req.query.code ){
req.session.game_id = 1
req.session.user_id = 1
res.redirect('/', 302);
} else {
res.redirect('/404.html', 404);
}
})
app.listen(3010);
C("BrowserComm - Express server listening on port %d in %s mode", app.address().port, app.settings.env);
io.set('transports', [
'websocket',
'htmlfile',
'xhr-polling',
'jsonp-polling',
]);
io.set('log level', 3);
// http://www.danielbaulig.de/socket-ioexpress/
var parseCookie = require('connect').utils.parseCookie;
var Session = require('connect').middleware.session.Session;
// only happens ONCE, per tab
io.set('authorization', function (data, accept) {
C( data.headers )
// TODO check session params
// check if there's a cookie header
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function (err, session) {
if (err) {
// if we cannot grab a session, turn down the connection
accept(err.message.toString()+'. u mad?', false);
} else {
// create a session object, passing data as request and our just acquired session data
data.session = new Session(data, session);
C('authorization #WIN!')
accept(null, true);
}
});
C('biscoito:', data.cookie)
} else {
// if there isn't, turn down the connection with a message
accept('No cookie transmitted. u mad?', false);
}
});
io.sockets.on('connection', function (socket) {
//console.log('A socket connected!');
C('A socket connected! sessionID:', socket.handshake.sessionID);
// setup an inteval that will keep our session fresh
var intervalID = setInterval(function () {
socket.handshake.session.reload( function () {
socket.handshake.session.touch().save();
});
}, 60 * 1000);
socket.emit('welcome', ['ok'] );
socket.on('gameStart', function (data) {
C("msg from:", socket.handshake.session.user_id, ':', data);
});
socket.on('disconnect', function () {
console.log('A socket with sessionID', socket.handshake.sessionID, 'disconnected!');
// clear the socket interval to stop refreshing the session
clearInterval(intervalID);
});
});
fps@piolho:~/workspace/browsercomm$ node-dev app.js
6 Sep 15:12:56 - [INFO] Started
info - socket.io started
BrowserComm - Express server listening on port 3010 in development mode
New Player! { code: '123456' }
GET /qrcode?code=123456 302 5ms
/ { host: '127.0.0.1:3010',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/10.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'en-US,en;q=0.8',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
cookie: 'connect.sid=fqt5vdo8Fs2hJoNZ758T8fRB.trusPHSQbrELk%2Fnl2UfdezTSLOYcrkFU7ft9XIO%2BYqY; express.sid=OsAtH5HkUK2W5il4N6Mk8KuL.HU2aMCY9ACIdexFWvgqlf3XODm4Mqx1QL3VwpGZ1EII' }
GET / 200 7ms
GET /stylesheets/style.css 304 3ms
GET /images/lasagna.gif 304 2ms
debug - served static /socket.io.js
{ host: 'localhost:3010',
connection: 'keep-alive',
referer: 'http://127.0.0.1:3010/',
'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/10.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30',
accept: '*/*',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'en-US,en;q=0.8',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' }
debug - authorized
warn - handshake error No cookie transmitted. u mad?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment