我正在使用 NODE.JS 和 socket.IO 做一个实验性的在线扑克游戏。游戏需要 3 名玩家加入才能开始。我使用 socket.IO 来监听加入玩家的连接。每当有3名玩家来时,他们将组成一个小组。目前我使用一些共享变量来做到这一点。但是如果有很多玩家同时进来,我担心会导致同步问题。从代码片段中可以看出,播放器、组、groupNumber、comingPlayer、客户端都在多个“连接”事件处理程序之间共享。因此,当一个事件处理程序被执行并且另一个事件处理程序被 V8 引擎调度时,它可能会破坏这些共享变量的状态。
我使用谷歌做了一些研究,但没有找到满意的答案。所以我在这里发帖看看有没有专家可以帮助我。提前致谢!
var clients = {}; // {"player1": 1} {"player2": 1} {"player3": 1}
var groups = {}; // {"1": ["player1", "player2", "player3"]
var groupNumber = 1; // the current group number
var comingPlayers = 0; // a temporary variable for the coming players
var players = []; // a temporary array containing the players which have not formed 1 group
socket.on('connection', function(client) {
sockets[client.id] = client;
players.push(client.id);
clients[client.id] = groupNumber;
comingPlayers++;
if (comingPlayers === 3) { // now there are 3 players which can compose 1 group
groups[groupNumber] = arrayClone(players);
gamePlay(groupNumber);
players = [];
groupNumber++;
comingPlayers = 0;
}
}