antimony

drive firefox from node.js
git clone https://wehaveforgeathome.hates.computer/antimony.git
Log | Files | Refs | Submodules | LICENSE

server.js (1527B)


      1 var http = require('http'),
      2     router = require('./router');
      3 
      4 var id = 0;
      5 var pushRes = null;
      6 var clientMessages = [];
      7 var clientResponses = {};
      8 
      9 var forwardNextMessage = function () {
     10   if (!pushRes) { return; }
     11   if (clientMessages.length === 0) { return; }
     12   var message = clientMessages.shift();
     13   var res = clientResponses[message.id];
     14   var json = message.json;
     15   pushRes.writeHead(200, {'Content-Type': 'application/json'});
     16   pushRes.end(json);
     17   pushRes = null;
     18   console.log('forwarded ' + message.id);
     19 };
     20 
     21 http.createServer(function (req, res) {
     22   pushRes = res;
     23   forwardNextMessage();
     24 }).listen(1234);
     25 
     26 router.post('client', function (req, res) {
     27 
     28   var json = '';
     29   req.on('data', function (data) { json += data; });
     30   req.on('end', function (data) {
     31     if (data) { json += data; }
     32 
     33     id++;
     34     var data = JSON.parse(json);
     35     data.id = id;
     36     json = JSON.stringify(data);
     37     clientMessages.push({ id: id, json: json});
     38     clientResponses[id] = res;
     39     console.log('saved ' + id);
     40     forwardNextMessage();
     41   });
     42 });
     43 
     44 router.post('browser/:id', function (req, res, id) {
     45 
     46   var json = '';
     47   req.on('data', function (data) { json += data; });
     48   req.on('end', function (data) {
     49     if (data) { json += data; }
     50     var clientRes = clientResponses[id];
     51     delete clientResponses[id];
     52     clientRes.writeHead(200);
     53     clientRes.end(json);
     54     res.writeHead(204);
     55     res.end();
     56     console.log('responded to ' + id);
     57   });
     58 });
     59 
     60 router.server.listen(1235);
     61 console.log('listening at http://localhost:1235');