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

黄色,

所以,我正在做一个多人在线游戏节点(为funzies),我困在一个问题已经一个多星期了。 也许解决方法很简单,但我忘了它。 长话短说:

  1. 数据从客户端发送到服务器,这个emit每16.66ms发生一次。
  2. 服务器正确接收它们,我们收集所有的数据(在这种情况下,大量的火球)。 我们把它们保存在player.skills_to_execute数组中。
  3. 每5秒钟,我们将数据复制到单独的数组( player_information ),因为我们是现在的一个,所以它可以不断收集新的数据,然后把所有收集到的数据发送回客户端。

问题肯定是在服务器端。 有时候这是有效的,有时却不行。 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); 

也许有人有什么想法?

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

尝试这个:

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

阅读更多关于在JavaScript中通过值或引用来复制数组的方法 :在JavaScript中通过值复制数组