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

user2716281
  • 155
  • 3
  • 11

1 Answers1

2

NodeJS Clusters are based on Nodejs Child Processes. In child processes you can send data between parent (Master in cluster) and child (worker in cluster) via messages over IPC channel. You can do the same with clusters using message events

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
    })
};
Gurbakhshish Singh
  • 1,034
  • 1
  • 10
  • 25
  • this might require some cleanup – Gurbakhshish Singh Nov 14 '16 at 21:02
  • Thanks for the reply, i have tried this method but when a player logs in the player list is updated on each worker directly and i had some problems where if i had two users on at the same time it would glith. – user2716281 Nov 14 '16 at 21:16
  • I managed to get it working but when I do for example playerlist[0].move() it says there is not a function I think this to do with Json stringify function it to send to the workers. – user2716281 Nov 14 '16 at 22:06
  • Managed to get two players from different workers on screen, but there is still some sync issues was wondering if you would be able to look at my git code and see if i have done anything wrong? – user2716281 Nov 14 '16 at 23:02