示例:发送套接字对象
\Example: sending a socket object
同样,sendHandler 参数可用于将套接字句柄传递给子进程。下面的示例生成两个子节点,每个子节点处理具有 "normal" 或 "special" 优先级的连接:
\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 { createServer } = require('node:net'); 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 = 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);import { fork } from 'node:child_process'; import { createServer } from 'node:net'; 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 = 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);
subprocess.js 将接收套接字句柄作为传递给事件回调函数的第二个参数:
\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`);
}
}
}); 不要在已传递给子进程的套接字上使用 .maxConnections。父级无法跟踪套接字何时被销毁。
\Do not use .maxConnections on a socket that has been passed to a subprocess.
The parent cannot track when the socket is destroyed.
子进程中的任何 'message' 处理程序都应验证 socket 是否存在,因为在将连接发送给子进程期间连接可能已关闭。
\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.