-
-
Save lqqyt2423/275e4773a3bac735888b8ab37d8dd0da to your computer and use it in GitHub Desktop.
node 父进程共享TCP server 给子进程
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 连接随机触发父进程或子进程的 connection handler | |
// parent.js | |
'use strict'; | |
const sub = require('child_process').fork('sub.js'); | |
// Open up the server object and send the handle | |
const server = require('net').createServer(); | |
server.on('connection', socket => { | |
socket.end('handled by parent'); | |
}); | |
server.listen(1337, () => { | |
sub.send('server', server); | |
}); | |
// sub.js | |
'use strict'; | |
process.on('message', function (m, server) { | |
if (m === 'server') { | |
server.on('connection', socket => { | |
socket.end('handled by child'); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment