简体   繁体   English

Node.js集群未监听

[英]Node.js Cluster not listening

I am trying to build a "Hello World" multi-process node.js HTTP server. 我正在尝试构建“ Hello World”多进程node.js HTTP服务器。

Using the code samples provided in the node docs here I can't get the "listening" event to fire, and thus an HTTP server to respond to requests. 使用此处的节点文档中提供的代码示例,我无法触发“监听”事件,因此无法通过HTTP服务器响应请求。 I am, however, getting the "online" event to fire. 但是,我正在触发“在线”事件。

How can I get this server to respond to requests? 如何使该服务器响应请求?

I'm running on OSX 10.8.4, node v0.10.7. 我正在OSX 10.8.4节点v0.10.7上运行。

Here's what I have: 这是我所拥有的:

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);
}

I fixed the issue by running the file directly. 我通过直接运行文件解决了该问题。 Previously, I ran server.js which was a one liner: 之前,我运行过server.js,它是一个内衬:

server.js server.js

require("./server/app.js");

server/app.js (code snippet in the question) server / app.js (问题中的代码段)

By running node app.js instead of node server.js the cluster started listening. 通过运行node app.js而不是node server.js ,集群开始侦听。 Not sure why this made a difference. 不知道为什么会有所作为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM