-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
116 lines (100 loc) · 3.11 KB
/
server.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
(function () {
'use strict';
var http = require('http');
var url = require('url');
var fs = require('fs');
var otherIp = null;
var port = 3333;
var myProperties = [];
var otherProperties = [];
var myValues = [];
var otherValues = [];
function handleRequest(req, res) {
var l = 0;
var i = 0;
var value = 0;
if (req.url === '/poll') {
var response = '';
l = otherProperties.length;
for (; i < l; ++i) {
response += otherProperties[i] + ' ' + otherValues[i] + '\n';
}
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(response);
} else if (req.url.indexOf('other') !== -1) {
l = otherProperties.length;
for (; i < l; ++i) {
if (req.url.indexOf(otherProperties[i]) !== -1) {
value = req.url.substring(req.url.lastIndexOf('/') + 1);
otherValues[i] = value;
break;
}
}
res.end();
} else {
l = myProperties.length;
for (; i < l; ++i) {
if (req.url.indexOf(myProperties[i]) !== -1) {
value = req.url.substring(req.url.lastIndexOf('/') + 1);
myValues[i] = value;
sendRequest(otherProperties[i], value);
break;
}
}
res.end();
}
}
function sendRequest(property, value) {
var options = {
host: otherIp,
port: port,
path: '/other/' + property + '/' + value
};
http.get(options).on('error', function (e) {
console.log("Error: " + e.message);
});
}
function start() {
http.createServer(handleRequest).listen(port);
console.log('Server running at http://localhost:' + port);
}
function addMyProperty(prop) {
myProperties.push(prop);
}
function addOtherProperty(prop) {
otherProperties.push(prop);
}
function setIp(ip) {
otherIp = ip;
}
function setPort(p) {
port = p;
}
function setupWithExtension(filepath, next) {
fs.readFile(filepath, 'utf-8', function (err, fileContents) {
if (err) {
next(err);
} else {
var extension = JSON.parse(fileContents);
setPort(extension.extensionPort);
for (var i = 0; i < extension.blockSpecs.length; ++i) {
var prop = extension.blockSpecs[i];
if (prop[0] === ' ') {
addMyProperty(prop[2]);
} else {
addOtherProperty(prop[2]);
}
}
next();
}
});
}
module.exports = {
start: start,
addMyProperty: addMyProperty,
addOtherProperty: addOtherProperty,
setIp: setIp,
setPort: setPort,
setupWithExtension: setupWithExtension
};
})();