我正在尝试构建一个“Hello World”多进程 node.js HTTP 服务器。
使用此处节点文档中提供的代码示例,我无法触发“监听”事件,因此无法让 HTTP 服务器响应请求。但是,我正在启动“在线”事件。
我怎样才能让这个服务器响应请求?
我在 OSX 10.8.4,节点 v0.10.7 上运行。
这是我所拥有的:
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function(worker) {
console.log('A worker with #' + worker.id);
});
cluster.on('listening', function(worker, address) {
console.log('A worker is now connected to ' + address.address + ':' + address.port);
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// 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');
}).listen(8000);
}