具有多个节点的多人游戏服务器

时间:2016-02-03 18:31:37

标签: node.js nginx redis load-balancing socket.io-redis

说你正在制作一个反恐精英服务器。我们有一个单独的大厅和多个房间,可以进行游戏。

I.E我有3个节点服务器,nginx负载均衡器,redis。

SCHEMA

我使用socket.io,使用redis适配器,所以我可以向任何服务器上的每个客户端发送消息。

我无法理解一件事。例如,我有这样的事情:

    var currentGames = {};


socket.on('createGame', function(gameName){
  var game = new Game();
  game.addPlayer(socket.id);


  currentGames.push();

  // ... Send to all clients, that game created and they can join
});

socket.on('joinGame', function(gameName){
  currentGames[gameName].addPlayer(socket.id);

  // ... Send to all players of this game, that player joined
});


socket.on('walk', function(gameName, coordinates){
   currentGames[socket.id].walk(player, coordinates);

   // ... Get all players positions and send to clients
});


class Game
{
  gameName;
  players = {};
  score;

  constructor(name){
    this.gameName = name;
  }

  addPlayer(player){
    players[name] = new Player(player);
  }

  walk(id, coordinates){
    this.players[id].updatePosition(coordinates);
  }  
}

class player
{
  id;
  life = 100;
  coordinates = {0,0,0};
  kills;
  death;

  constructor(id){
    this.id = id;
  }

  updatePosition(coords){
    this.coordinates = coords;
  }


}

我刚刚编写了这段代码。

let,user_1在node-1上,user-2在node-2上。

如果user_1创建游戏,则将创建实例并将其保存在节点-1上。

所以当user_2收到有关游戏的信息时,会创建并点击一个加入按钮, 客户端将向服务器发送请求,在节点2上,不会成为user_1创建的游戏实例。

我希望,你会明白,我在说什么(我的英语并不好)。

我想,对于所有节点,游戏实例的currentGames对象必须是全局的。但我不知道如何。

我应该使用redis或mongo或其他东西来存储游戏信息,而不是variable吗?

我走错路吗?

1 个答案:

答案 0 :(得分:0)

你应该在Redis,房间和游戏实例中同步游戏状态 我有一些注意事项:
+实体状态 - 管理游戏状态,存储和设置,获取游戏信息给Redis
+客户端状态 - 每个连接客户端都有客户端状态和与实体状态同步,每个勾选在游戏循环中,你检查实体状态和客户端状态之间的差异,并将其发送给客户端并更新游戏客户端

相关问题