Socket.io在服务器端丢失数据

时间:2016-03-03 10:35:19

标签: node.js socket.io multiplayer

黄色,

所以,我在节点上做了一个多人在线游戏(为了游戏)而且我现在已经遇到了一个多星期的问题了。也许解决方案很简单,但我对它毫不知情。 长话短说:

  1. 数据从客户端发送到服务器,每次emit都会发生 16.66ms。
  2. 服务器正确接收它们,我们收集所有数据(很多 在这种情况下的火球)。我们将它们保存在player.skills_to_execute中 阵列。
  3. 每隔5秒,我们将数据复制到单独的数组(player_information),因为 我们是当前的清洁,所以它可以继续收集新的 数据,然后我们将所有收集的数据发送回客户端。
  4. 问题肯定在服务器端。 有时这会有效,有时它不会。 player_information是我发送回前面的数组,但在发送之前,我会检查服务器上的console.log,如果它确实包含数据,它确实!但不知何故,数据在发送之前被删除/覆盖并且它发送空数组(因为我检查前端并且我收到空的)。

    代码相当复杂,但我已将其最小化,因此更容易理解。

    此代码保留在客户端,并按原样运行:

    // front.js
    socket.on("update-player-information", function(player_data_from_server){
       console.log( player_data_from_server.skills_to_execute );
    });
    
    socket.emit("update-player-information", {
        skills_to_execute: "fireball"
    });
    

    此代码保留在服务器端,并按预期工作:

    // server.js    
    socket.on("update-player-information", function(data){
    
       // only update if there are actually skills received
       // we dont want every request here to overwrite actual array with empty []                     // data.skills_to_execute = this will usually be 1 to few skills that are in need to be executed on a single client cycle
       // naturally, we receive multiple requests in these 5 seconds, 
       // so we save them all in player object, where it has an array for this
    
       if ( data.skills_to_execute.length > 0 ) {
          player.skills_to_execute.push( data.skills_to_execute );    
       }
    
    });
    

    现在这是代码,狗屎袭击了粉丝。

    // server.js
    // Update player information
    setInterval(function(){
       // for every cycle, reset the bulk data that we are gona send, just to be safe
       var player_information = [];
    
       // collect the data from player
       player_information.push(
          { 
             skills_to_execute: player.skills_to_execute
          }
       );
    
       // we reset the collected actions here, cause they are now gona be sent to front.js
       // and we want to keep collecting new skills_to_execute that come in
       player.skills_to_execute = [];
    
       socket.emit("update-player-information", player_information);
    
    }, 5000);
    

    也许有人有任何想法吗?

1 个答案:

答案 0 :(得分:1)

按值而不是按引用复制数组。

试试这个:

player_information.push(
  { 
     skills_to_execute: player.skills_to_execute.slice()
  }
);

详细了解如何按值或通过引用在JavaScript中复制数组:Copying array by value in JavaScript