child_process 发送句柄问题
我用 child_process 发送 server 以后,测试时只有最后一个进程能接受请求,和书上讲的不一样,求大神指点,谢谢! 测试环境:win10, node v0.12.7
代码如下
parent.js
var cp = require('child_process');
var child1 = cp.fork('child.js');
var child2 = cp.fork('child.js');
var server = require('net').createServer();
server.listen(1337, function () {
console.log('parent listening!');
child1.send('server', server);
child2.send('server', server);
});
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.pid + '\n');
});
process.on('message', function (m, tcp) {
console.log(process.pid);
if (m === 'server') {
tcp.on('connection', function (socket) {
server.emit('connection', socket);
});
}
});