-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserverSyncCluster.js
63 lines (60 loc) · 2.73 KB
/
serverSyncCluster.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
/*-----------------------------------------------------------------------------+
| Cluster/Async I/O Benchmark Version 2.0.0 |
+------------------------------------------------+----------------------------+
| Copyright 2014, Synthetic Semantics LLC | http://synsem.com/ |
| Copyright 2015-2017, Jace A Mogill | [email protected] |
| Released under the Revised BSD License | [email protected] |
+------------------------------------------------+----------------------------*/
var config = require('./config.json');
var fs = require("fs");
var http = require('http');
var url_module = require("url");
var cluster = require('cluster');
if (cluster.isMaster) {
for (var i = 0; i < config.nServers; i++)
cluster.fork();
} else {
http.createServer(function (request, response) {
var key = url_module.parse(request.url).query.replace('key=', '');
switch (request.method) {
case 'GET':
var sum = 0;
var allFiles = "";
for (var i = 0; i < config.nTimes; i++) {
var file = fs.readFileSync(config.dataPath + key, 'utf8');
allFiles += file;
sum += JSON
.parse(file)
.sort()
.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
});
}
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(sum.toString() + JSON.stringify(allFiles));
break;
case 'POST':
var postData = '';
request
.on('data', function (data) {
postData += data;
})
.on('end', function () {
try {
fs.writeFileSync(config.dataPath + key, postData);
}
catch (err) {
response.writeHead(400, {'Content-Type': 'text/plain'});
response.end('Error: Unable to write file?' + err);
}
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('success');
});
break;
default:
response.writeHead(400, {'Content-Type': 'text/plain'});
response.end("Error: Bad HTTP method: " + request.method);
}
}).listen(config.serverPort);
console.log('synchronous server is running: PID=', cluster.worker.process.pid);
}