forked from filippofinke/layer7-dstat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (43 loc) · 1.14 KB
/
index.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
const http = require("http");
const fs = require("fs");
const WebSocket = require("ws");
const cluster = require("cluster");
const os = require("os");
const cpus = os.cpus().length;
const port = 8080;
const index = fs.readFileSync("./index.html");
if (cluster.isMaster) {
console.log(`Number of CPUs is ${cpus}`);
console.log(`Master ${process.pid} is running`);
let requests = 0;
let childs = [];
for (let i = 0; i < cpus; i++) {
let child = cluster.fork();
child.on("message", (msg) => {
requests++;
});
childs.push(child);
}
setInterval(() => {
for (let child of childs) {
child.send(requests);
}
requests = 0;
}, 1000);
} else {
console.log(`Worker ${process.pid} started`);
const handler = function (req, res) {
if (req.url == "/") {
process.send(0);
res.end();
} else {
res.end(index);
}
};
const server = http.createServer(handler);
const wss = new WebSocket.Server({ server });
process.on("message", (requests) => {
wss.clients.forEach((client) => client.send(requests));
});
server.listen(port);
}