3

So I have setup a simple nodejs cluster game, I am new to nodejs. basically players connect to to my worker using socket.io then they get created to a Player Object then added to my PlayerManager.LIST array. Now this causes me some issues as the PlayerManager.LIST is on each of workers and are not sync'd.

So my question is, is there a better way of doing this so that if I connect to worker 2 I see same player list as worker 1's.

Structure at the moment:

app.js
-> worker
->-> PlayerManager (Contains List)
->->-> Player

Git Repo: https://github.com/mrhid6/game_app_v2

4

1 回答 1

2

NodeJS 集群基于 Nodejs 子进程。在子进程中,您可以通过 IPC 通道上的消息在父进程(集群中的 Master)和子进程(集群中的工作者)之间发送数据。您可以使用消息事件对集群执行相同的操作

var cluster = require('cluster');
var _ = require('lodash');
var http = require('http');
var workers = [];
var workerCount = 4;

if (cluster.isMaster) {
  for (var i = 0; i < workerCount; i++) {
    var worker = cluster.fork();

    worker.on('message', function(msg) {
      if (msg.task === 'sync') {
            syncPlayerList(msg.data);
      }
    });
  }
  workers.push[worker];

} else {
  var worker = new Worker();
  process.on('message', function(msg) {
    if (msg.task === 'sync') {
        worker.playerList = msg.data;
    }
  });
}

function syncPlayerList (playerList) {
    _.forEach(workers, function (worker) {
        worker.send({
            task: 'sync',
            data: playerList
        });
    });
};


// worker class
function Worker() {
    this.playerList = [];
}

Worker.prototype.sendSyncEvent = function () {
    process.send({
        task: 'sync',
        data: this.playerList
    })
};
于 2016-11-14T21:01:40.307 回答