0

我正在使用 peer.js 并试图将所有传入连接存储在一个数组中。

应用背景:电脑作为主控台。电话使用控制台对等 ID 连接到控制台,并将其对等 ID 发送给控制台。控制台然后读取每个对等 id 并与之创建数据连接

我试图将连接存储在一个数组中,然后我可以在我需要的任何函数中调用连接。当我尝试将连接传递给函数“SendPhonePlayerDetails”时,连接打印为未定义。

//establish a connection
//data.pid is the peer id of the phone
connections[current_player] = peer.connect(data.pid);

setTimeout(function() {
  sendPhonePlayerDetails(connections[current_player]);  
},'2000');

function sendPhonePlayerDetails(connection)
{ 
   console.log(connection) //prints undefined;
   player_num = Object.size(players); //get the player number
   player_name = players["p" + player_num][1] //get the players name

   //send data to the phone
   setTimeout(function() {
        send_data({player_number: player_num, player_name: player_name }, connection);
   },'2000');

   //if not player 1 notify them who is the leader
   if(player_num > 1){
      setTimeout(function() {
          send_data({controlling: players["p1"][1] }, connection);
      },'2000');
   }

}


function send_data(data, connection)
{
   if (!connection) return;
   connection.send(data); //send the data to the phone
}
4

1 回答 1

0

连接数组没有被解释为全局。通过添加“window.”,我能够控制日志并传递连接数组。

setTimeout(function() {
  sendPhonePlayerDetails(window.connections['p' + (current_player-1)]);  
},'2000');
于 2016-07-29T19:54:39.113 回答