NodeJs多進程和socket.io通信

1、開啓多進程web

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);
    }
}

 

2、啓動websocket服務-------(a.js)websocket

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);
});

 

3、DEMO演示截圖socket

一、服務端啓動程序ui

 二、客戶端1socket.io

 

三、客戶端2spa

四、客戶端3code

五、客戶端4router

相關文章
相關標籤/搜索