6

検討:

// Parent

var child = require('child_process').fork('child.js');

// Open up the server object and send the handle.
var server = require('net').createServer();
server.on('connection', function (socket) {
  socket.end('handled by parent');
});
server.listen(1337, function() {
  child.send('server', server);
});

//Child
process.on('message', function(m, server) {
  if (m === 'server') {
    server.on('connection', function (socket) {
      socket.end('handled by child');
    });
  }
});

上記の例に示すように、親はサーバー オブジェクトを子プロセスに送信するため、子でもクライアント接続要求の一部を処理できます。

Node.jsでどのように達成されますか?

4

3 に答える 3

5

Here is what node does when process.send is called with a handle argument.

And after reading that, the handleConversion function is also interesting to read.

I don't fully understand it yet, but I think essentially the state of the socket/server is serialized and passed between master/worker using IPC. Maybe the state being passed around is enough for each process to bind itself to the socket? Or maybe the parent is keeping a registry of children who can handle any given socket, so once a new connection comes in for some socket, it is sent to a child that registered for it. That part I am less sure about.

于 2013-12-07T22:19:58.450 に答える
2

Node.jsクラスターモジュールをご覧になることをお勧めします。

ワーカーを呼び出すserver.listen(...)と、引数がシリアル化され、要求がマスタープロセスに渡されます。マスタープロセスにワーカーの要件に一致するリスニングサーバーがすでにある場合は、ハンドルをワーカーに渡します。その要件に一致するリスニングサーバーがまだない場合は、リスニングサーバーを作成し、ハンドルを子に渡します。

ドキュメントからの完全な例:

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('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case it's an HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}
于 2012-11-28T12:32:13.747 に答える