Skip to content

Instantly share code, notes, and snippets.

@lqqyt2423
Last active February 27, 2019 03:07
Show Gist options
  • Save lqqyt2423/640bbae5d9ebd6131d27b5bed6fdf496 to your computer and use it in GitHub Desktop.
Save lqqyt2423/640bbae5d9ebd6131d27b5bed6fdf496 to your computer and use it in GitHub Desktop.
node 多个子进程监听相同 http 端口
// 连接随机选择任一一个子进程
// 由于独立启动的进程互相之间并不知道文件描述符,所以监听相同端口时就会失败。
// 但对于 send()发送的句柄还原出来的服务而言,它们的文件描述符是相同的,
// 所以监听相同端口不会引起异常
// 多个应用监听相同端口时,文件描述符同一时间只能被某个进程所用。换言之就是网络请求
// 向服务器端发送时,只有一个幸运的进程能够抢到连接,也就是说只有它能为这个请求进行服务。
// 这些进程服务是抢占式的。
// parent.js
'use strict';
const cp = require('child_process');
const sub1 = cp.fork('sub.js');
const sub2 = cp.fork('sub.js');
// Open up the server object and send the handle
const server = require('net').createServer();
server.listen(1337, () => {
sub1.send('server', server);
sub2.send('server', server);
// 关掉
server.close();
});
// sub.js
'use strict';
const http = require('http');
const server = http.createServer(function (req, res) {
res.writeHead(200, { 'Contenty-Type': 'text/plain' });
res.end('handled by child, pid is ' + process.pid + '\n');
});
process.on('message', function (m, tcp) {
if (m === 'server') {
tcp.on('connection', socket => {
// explicitly emitted by users to inject connections into the HTTP server
server.emit('connection', socket);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment