Created
April 15, 2014 08:51
-
-
Save mekegi/10715029 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global Buffer: false, clearInterval: false, clearTimeout: false, console: false, exports: false, | |
global: false, module: false, process: false, querystring: false, | |
require: false, setInterval: false, setTimeout: false, '__filename': false, '__dirname': false */ | |
"use strict"; | |
var dataArrayByCanal = [], | |
port = process.argv[2]; | |
if (port === undefined) { | |
console.log('Error: Port is not specified. Port must be passed as first argument'); | |
process.exit(1); | |
} | |
var isCacheable = process.argv[3] === 'cache', | |
http = require('http'), | |
url = require('url'), | |
formidable = require('/usr/local/lib/node_modules/formidable'); | |
var ClientManager = function () { | |
var clients = [], | |
me = this; | |
this.registerClient = function (canal, client) { | |
if (!clients[canal]) { | |
clients[canal] = []; | |
} | |
clients[canal].push(client); | |
}; | |
this.broadcastData = function (canal, data) { | |
var i; | |
if (clients[canal]) { | |
for (i = 0; i < clients[canal].length; i += 1) { | |
me.writeData(clients[canal][i], data); | |
} | |
clients[canal] = []; | |
} | |
}; | |
this.writeData = function (res, data) { | |
res.writeHeader(200, {'Content-Type': 'application/json;charset=utf-8'}); | |
res.write(data, 'utf-8'); | |
res.end(); | |
}; | |
}, | |
clientManager = new ClientManager(); | |
http.createServer(function (req, res) { | |
var urlParsed = url.parse(req.url, true), | |
canal = urlParsed.query.canal, | |
form; | |
switch (urlParsed.pathname) { | |
case '/publish': | |
form = new formidable.IncomingForm(); | |
form.parse(req, function (err, fields, files) { | |
var data = fields.data || ''; | |
if (!isCacheable || dataArrayByCanal[canal] !== data) { | |
if (isCacheable) { | |
dataArrayByCanal[canal] = data; | |
} | |
clientManager.broadcastData(canal, data); | |
console.log('publish to ' + canal + ' canal'); | |
} | |
clientManager.writeData(res, 'ok'); | |
}); | |
break; | |
case '/subscribe': | |
clientManager.registerClient(canal, res); | |
if (isCacheable && dataArrayByCanal[canal] && urlParsed.query.first) { | |
console.log(console.log('publish to ' + canal + ' canal during subscribe')); | |
clientManager.broadcastData(canal, dataArrayByCanal[canal]); | |
} | |
console.log('subscribe to ' + canal + ' canal'); | |
break; | |
} | |
}).listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment