Nodejs multi-process and Socket.io communication-demo

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.