使用文件描述符传递实现自己的cluster

2020-12-14 10:50:32 浏览数 (1)

parent.js

代码语言:javascript复制
const childProcess = require('child_process');
const net = require('net');
const workers = [];
const workerNum = 10    ;
const handle = net._createServerHandle('127.0.0.1', 11111, 4);
for (let i = 0; i < workerNum; i  ) {
    const worker = childProcess.fork('child.js', {env: {index: i}});
    workers.push(worker);
    worker.send(null ,handle);
}

child.js

代码语言:javascript复制
const net = require('net');
process.on('message', (message, handle) => {
    net.createServer(() => {
        console.log(process.env.index, 'receive connection');
    }).listen({handle, port: 11111});
});

client.js

代码语言:javascript复制
const net = require('net');
for (let i = 0; i < 50; i  ) {
    net.connect({port: 11111});
}

测试:执行parent.js,然后执行client.js。

0 人点赞