First, open the multi-process
Const OS = require (' OS '); const CP= Require (' child_process '); Const Forklist={};const Forkprefix= ' Fork_ '; let Cpuslen=Os.cpus (). Length;let Port= 9562; for(vari = 1; I <= Cpuslen; i++) {Forklist[forkprefix+ i] = cp.fork (' ${__dirname}/a.js ', [port]);varChildpid = Forklist[forkprefix +I].pid; Console.log ("Sub-process fork succeeded." Pid: "+childpid); Port++;}//listening for child process distribution messagesvarPID =Process.pid; for(varKeyinchforklist) { varForkobj =Forklist[key]; varChildpid =Forkobj.pid; Forkobj.on (' Message ', (m) = ={Console.log (' Main process ID: ' + pid + ', Child process ID: ' + childpid + ', message: ', M); Send (m); });}//Poll All child process messages sentfunctionSend (m) { for(varKeyinchforklist) {forklist[key].send (M); }}
Second, start WebSocket service-------(a.js)
varPID =Process.pid;console.log (' Starting Socket.io server ... ', PID);varArgvs = Process.argv.slice (2);if(argvs.length <= 0) {Console.log ("Fork child params Bad ..."); return false;}varPort = argvs[0];varServer = require (' http '). Createserver ();varIO = require (' Socket.io ') (server); Io.on (' Connection ',function(socket) {Socket.on (' Router ',function(data) {Console.log (data); //send a message to the main process, distributed by the main process to all child processesprocess.send (data); }); Socket.on (' Disconnect ',function () { });}); Server.listen (port);//listening for messages distributed by the main processProcess.on (' message ', (m) = ={Console.log (' PID: ' + pid + ', Message: ', M); Io.sockets.emit (' Router ', M);});
Three, demo demo
1. Service-side Start-Up program
2, Client 1
3, Client 2
4, Client 3
5, Client 4
Nodejs Multi-process and Socket.io communication-demo