In practice, it will be handled with PM2, just to understand the principles and network modules
Tutorial: http://taobaofed.org/blog/2015/11/03/nodejs-cluster/
Correction: Net.createserverhandle ();
Entries: http://www.jianshu.com/p/54b85f278695
Code:
Master
Const NET = require (' net '); const fork = require (' child_process '). Fork;var handle = Net.createserverhandle (' 0.0.0.0 ', for (Var i=0;i<4;i++) { fork ('./worker '). Send ({}, handle);}
Worker
Const NET = require (' net ');p rocess.on (' message ', function (m, handle) { start (handle);}); var buf = ' Hello Nodejs '; var res = [' http/1.1 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);} }
Explanation, fork ('/worker)->emit (' message ')
Nodejs Load Balancing