Skip to content

Instantly share code, notes, and snippets.

@fwon
Created August 26, 2014 16:42
Show Gist options
  • Save fwon/41290307656114e9a4b1 to your computer and use it in GitHub Desktop.
Save fwon/41290307656114e9a4b1 to your computer and use it in GitHub Desktop.
//父进程和子进程同时开启
//parent.js
var cp = require('child_process');
var child1 = cp.fork('child.js');
var child2 = cp.fork('child.js');
//open up the server object and send the handle
var server = require('net').createServer();
server.on('connection', function(socket) {
socket.end('handled by parent\n');
});
server.listen(1337, function() {
child1.send('server', server);
child2.send('server', server);
});
//child.js
process.on('message', function(m, server) {
if(m === 'server') {
server.on('connection', function(socket) {
socket.end('handled by child, pid is ' + process.pid + '\n');
});
}
});
//只开启子进程
//parent.js
var cp = require('child_process');
var child1 = cp.fork('child.js');
var child2 = cp.fork('child.js');
//open up the server object and send the handle
var server = require('net').createServer();
server.listen(1337, function() {
child1.send('server', server);
child2.send('server', server);
//关掉
server.close();
});
//child.js
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('handled by child, pid is ' + process.id + '\n');
});
process.on('message', function(m, tcp) {
if(m === 'server') {
tcp.on('connection', function(socket) {
server.emit('connection', socket);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment