示例:发送服务器对象
例如,可以使用 sendHandle
参数将 TCP 服务器对象的句柄传给子进程,如下例所示:
const subprocess = require('node:child_process').fork('subprocess.js');
// 打开服务器对象并发送句柄。
const server = require('node:net').createServer();
server.on('connection', (socket) => {
socket.end('handled by parent');
});
server.listen(1337, () => {
subprocess.send('server', server);
});
然后子进程将收到服务器对象:
process.on('message', (m, server) => {
if (m === 'server') {
server.on('connection', (socket) => {
socket.end('handled by child');
});
}
});
一旦服务器现在在父进程和子进程之间共享,则一些连接可以由父进程处理,一些连接由子进程处理。
虽然上面的示例使用使用 node:net
模块创建的服务器,但 node:dgram
模块服务器使用完全相同的工作流程,除了监听 'message'
事件而不是 'connection'
和使用 server.bind()
而不是 server.listen()
。
但是,目前仅在 Unix 平台上支持。
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 subprocess = require('node:child_process').fork('subprocess.js');
// Open up the server object and send the handle.
const server = require('node:net').createServer();
server.on('connection', (socket) => {
socket.end('handled by parent');
});
server.listen(1337, () => {
subprocess.send('server', server);
});
The child 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.
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, currently only
supported on Unix platforms.