示例:发送服务器对象


¥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.