您好我想学习节点js中的多线程。我现在正在学习,但我在节点js中遇到了一些麻烦。我在下面找到了这些代码。 当我想转到http://localhost/plumber地址时,为什么这些代码会出错? 感谢...
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var http = require('http');
if (cluster.isMaster) {
console.log (' Fork %s worker(s) from master', numCPUs);
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function(worker) {
console.log ('worker is running on %s pid', worker.process.pid);
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker with %s is closed', worker.process.pid);
});
} else if (cluster.isWorker) {
var port = 3000;
console.log('worker (%s) is now listening to http://localhost:%s',
cluster.worker.process.pid, port);
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
console.log(req.url+cluster.worker.process.pid);
if(req.url=='/plumber'){
sleep(10);
res.end('no write because of error but answer requests');
}else {
res.end('cluster' + cluster.worker.process.pid + 'answered');
}
}).listen(port,"127.0.0.1");
}
答案 0 :(得分:1)
首先,如果它不是默认值(80),您需要在网址中指定端口:
其次,sleep
不是一个功能;并且很可能它永远不会是您想要的方式,因为node.js在设计上是非阻塞的。您可能希望使用类似setTimeout
的内容。