nodejs work in cluster

nodejs小练习

直接上源码,ps(他的集群可以共享连接,共享端口,这点很赞)

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
var cluster = require('cluster');
var http = require('http');
var os = require('os');

var numCPUs = os.cpus().length;

var sleep = function(time_ms){
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + time_ms);
}

if (cluster.isMaster) {
// Master:
// Let's fork as many workers as you have CPU cores

for (var i = 0; i < numCPUs; ++i) {
cluster.fork();
}
} else {
// Worker:
// Let's spawn a HTTP server
// (Workers can share any TCP connection.
// In this case its a HTTP server)

http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n" + process.pid);
sleep(1000);
}).listen(8080);
}