Skip to content

Instantly share code, notes, and snippets.

@thefron
Created October 20, 2011 17:37
Show Gist options
  • Save thefron/1301755 to your computer and use it in GitHub Desktop.
Save thefron/1301755 to your computer and use it in GitHub Desktop.
Simple long polling
var http = require('http');
var net = require('net');
var url = require('url');
var connections = {};
var subscriber = http.createServer(function(req, res){
params = url.parse(req.url, true);
var channel = params.pathname;
channel = channel.substr(1, channel.length - 1);
if(params.query.callback){
res.callback_function = params.query.callback;
}
console.log('[ClIENT] Connected('+channel+')');
res.setHeader('Content-Type', 'application/json');
if(connections[channel] instanceof Array){
connections[channel].push(res);
}
else {
connections[channel] = [res];
}
}).listen(80);
var publisher = net.createServer(function(socket){
socket.setEncoding('utf8');
socket.on('data', function(data){
var chunks = data.split(' ');
if(chunks[0] == 'SEND'){
var channel = chunks[1];
console.log('[PUBLISH] Connected('+channel+')');
var content_length = parseInt(chunks[3]);
var json = data.slice(-content_length);
if(connections[channel] instanceof Array){
while(connections[channel].length){
var text;
var res = connections[channel].pop();
if(res.callback_function){
text = res.callback_function+'('+json+');';
}
else {
text = json;
}
console.log('[PUBLISH] ' + text);
res.end(text);
}
}
}
});
}).listen(3002);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment