示例:发送一个服务器对象


【Example: sending a server object】

sendHandle 参数可以用于,例如,将 TCP 服务器对象的句柄传递给子进程,如下面的示例所示:

【The sendHandle argument can be used, for instance, to pass the handle of a TCP server object to the child process as illustrated in the example below:】

const { fork } = require('node:child_process');
const { createServer } = require('node:net');

const subprocess = fork('subprocess.js');

// Open up the server object and send the handle.
const server = createServer();
server.on('connection', (socket) => {
  socket.end('handled by parent');
});
server.listen(1337, () => {
  subprocess.send('server', server);
});import { fork } from 'node:child_process';
import { createServer } from 'node:net';

const subprocess = fork('subprocess.js');

// Open up the server object and send the handle.
const server = createServer();
server.on('connection', (socket) => {
  socket.end('handled by parent');
});
server.listen(1337, () => {
  subprocess.send('server', server);
});

然后子进程将接收服务器对象:

【The child process would then receive the server object as:】

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

一旦服务器在父进程和子进程之间共享,部分连接可以由父进程处理,部分可以由子进程处理。

【Once the server is now shared between the parent and child, some connections can be handled by the parent and some by the child.】

虽然上面的示例使用的是通过 node:net 模块创建的服务器,node:dgram 模块服务器使用的工作流程完全相同,只是在监听事件时使用 'message' 代替 'connection',以及使用 server.bind() 代替 server.listen()。然而,这仅在 Unix 平台上受支持。

【While the example above uses a server created using the node:net module, node:dgram module servers use exactly the same workflow with the exceptions of listening on a 'message' event instead of 'connection' and using server.bind() instead of server.listen(). This is, however, only supported on Unix platforms.】