标签:
实际中会用pm2来处理,这里只是了解下原理和网络模块
教程:http://taobaofed.org/blog/2015/11/03/nodejs-cluster/
纠正:net.createServerHandle();
记录:http://www.jianshu.com/p/54b85f278695
代码:
master
const net = require(‘net‘); const fork = require(‘child_process‘).fork; var handle = net.createServerHandle(‘0.0.0.0‘, 3000); for(var i=0;i<4;i++) { fork(‘./worker‘).send({}, handle); }
worker
const net = require(‘net‘); process.on(‘message‘, function(m, handle) { start(handle); }); var buf = ‘hello nodejs‘; var res = [‘HTTP/1.1 200 OK‘,‘content-length:‘+buf.length].join(‘\r\n‘)+‘\r\n\r\n‘+buf; function start(server) { server.listen(); server.onconnection = function(err,handle) { console.log(‘got a connection on worker, pid = %d‘, process.pid); var socket = new net.Socket({ handle: handle }); socket.readable = socket.writable = true; socket.end(res); } }
解释,fork(‘/worker)->emit(‘message‘)
标签:
原文地址:http://www.cnblogs.com/wang-jing/p/5115807.html