示例:发送套接字对象


同样,sendHandler 参数可用于将套接字的句柄传给子进程。 下面的例子产生了两个子进程,每个子进程都处理具有“normal”或“special”优先级的连接:

const { fork } = require('node:child_process');
const normal = fork('subprocess.js', ['normal']);
const special = fork('subprocess.js', ['special']);

// 打开服务器并将套接字发送给子进程。
// 使用 pauseOnConnect 防止套接字在发送到子进程之前被读取。
const server = require('node:net').createServer({ pauseOnConnect: true });
server.on('connection', (socket) => {

  // 如果这是 special 优先级...
  if (socket.remoteAddress === '74.125.127.100') {
    special.send('socket', socket);
    return;
  }
  // 这是 normal 优先级。
  normal.send('socket', socket);
});
server.listen(1337);

subprocess.js 将接收套接字句柄作为传给事件回调函数的第二个参数:

process.on('message', (m, socket) => {
  if (m === 'socket') {
    if (socket) {
      // 检查客户端套接字是否存在。
      // 套接字可能会在发送和在子进程中接收到它之间关闭。
      socket.end(`Request handled with ${process.argv[2]} priority`);
    }
  }
});

不要在已传给子进程的套接字上使用 .maxConnections。 父进程无法跟踪套接字何时被销毁。

子进程中的任何 'message' 句柄都应验证 socket 是否存在,因为在将连接发送到子进程所需的时间内,连接可能已关闭。

Similarly, the sendHandler argument can be used to pass the handle of a socket to the child process. The example below spawns two children that each handle connections with "normal" or "special" priority:

const { fork } = require('node:child_process');
const normal = fork('subprocess.js', ['normal']);
const special = fork('subprocess.js', ['special']);

// Open up the server and send sockets to child. Use pauseOnConnect to prevent
// the sockets from being read before they are sent to the child process.
const server = require('node:net').createServer({ pauseOnConnect: true });
server.on('connection', (socket) => {

  // If this is special priority...
  if (socket.remoteAddress === '74.125.127.100') {
    special.send('socket', socket);
    return;
  }
  // This is normal priority.
  normal.send('socket', socket);
});
server.listen(1337);

The subprocess.js would receive the socket handle as the second argument passed to the event callback function:

process.on('message', (m, socket) => {
  if (m === 'socket') {
    if (socket) {
      // Check that the client socket exists.
      // It is possible for the socket to be closed between the time it is
      // sent and the time it is received in the child process.
      socket.end(`Request handled with ${process.argv[2]} priority`);
    }
  }
});

Do not use .maxConnections on a socket that has been passed to a subprocess. The parent cannot track when the socket is destroyed.

Any 'message' handlers in the subprocess should verify that socket exists, as the connection may have been closed during the time it takes to send the connection to the child.