NodeJs多进程和socket.io通讯
一、开启多进程
const os = require('os'); const cp = require('child_process'); const forkList = {}; const forkPrefix = 'fork_'; let cpusLen = os.cpus().length; let port = 9562; for (var i = 1; i <= cpusLen; i++) { forkList[forkPrefix + i] = cp.fork(`${__dirname}/a.js`, [port]); var childPid = forkList[forkPrefix + i].pid; console.log("子进程Fork成功.Pid:" + childPid); port++; } // 监听子进程分发消息 var pid = process.pid; for (var key in forkList) { var forkObj = forkList[key]; var childPid = forkObj.pid; forkObj.on('message', (m) => { console.log('主进程ID:' + pid + ',子进程ID:' + childPid + ',message:', m); send(m); }); } // 轮询所有子进程消息发送 function send(m) { for (var key in forkList) { forkList[key].send(m); } }
二、启动websocket服务-------(a.js)
var pid = process.pid; console.log('starting socket.io server......', pid); var argvs = process.argv.slice(2); if (argvs.length <= 0) { console.log("fork child params bad..."); return false; } var port = argvs[0]; var server = require('http').createServer(); var io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('router', function (data) { console.log(data); // 把消息发送给主进程,由主进程分发给所有子进程 process.send(data); }); socket.on('disconnect', function () { }); }); server.listen(port); // 监听由主进程分发消息 process.on('message', (m) => { console.log('pid:' + pid + ',message:', m); io.sockets.emit('router', m); });
三、DEMO演示截图
1、服务端启动程序
2、客户端1
3、客户端2
4、客户端3
5、客户端4