secret
Last active

A Message Wall With Long Poll Properties in Node.JS and Express

  • Download Gist
wall.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// our application server
var app = require( 'express' ).createServer( )
// a list of messages scrawled on the wall
var msgs = []
 
// a list of deferred responses
var defers = []
 
// / redirects to /q
app.get( '/', function(req, res){
res.redirect( '/q' )
} )
 
// /q[/<xxx>] query messages from the wall; may block for a protracted period
app.get( '/q/:ofs?', function(req, res){
var ofs = parseInt( req.params.ofs ) || 0
res.contentType( 'text/plain' )
if( msgs.length > ofs ){
// send all messages on the wall to the user, starting from ofs
res.send( msgs.slice( ofs ).join( '\n' ) + '\n' )
}else{
// waiting for the future; defer until it arrives
defers.push( [ ofs, res ] )
}
} )
 
// /p?msg=<xxx> post a message to the wall
app.get( '/p', function( req, res ){
var ix, msg = req.query.msg
if( msg ) msgs.push( msg )
// the future has arrived, notify all those who have deferred
msg = msg + '\n'
for( ix in defers ){
defers[ix].send( msg )
}
// now purge the deferrals
defers = []
} )
 
// listen to port 3000 for traffic.
app.listen( 3000 )

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.