如何在数组中存储对等连接

时间:2022-04-14 15:40:54

I am using peer.js and am trying to store all incoming connections in an array.

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

Background of App: Computer acts as main console. Phones connect to the console using the consoles peer id and sends the console it's peer id. The console then reads in each peer id and creates a data connection with it

应用程序背景:计算机充当主控台。电话使用控制台对等ID连接到控制台,并向控制台发送它的对等ID。然后,控制台读入每个对等ID并与其创建数据连接

I am trying to store the connections in an array and then I can call the connection in any function I need. When I try and pass the connection to the function 'SendPhonePlayerDetails' the connection prints out as undefined.

我试图将连接存储在一个数组中,然后我可以在我需要的任何函数中调用连接。当我尝试将连接传递给函数'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
}

1 个解决方案

#1


0  

The connections array was not being interpreted as global. By adding 'window.', I was able to console log and pass the connections array.

连接数组未被解释为全局。通过添加'window。',我能够控制日志并传递连接数组。

setTimeout(function() {
  sendPhonePlayerDetails(window.connections['p' + (current_player-1)]);  
},'2000');

#1


0  

The connections array was not being interpreted as global. By adding 'window.', I was able to console log and pass the connections array.

连接数组未被解释为全局。通过添加'window。',我能够控制日志并传递连接数组。

setTimeout(function() {
  sendPhonePlayerDetails(window.connections['p' + (current_player-1)]);  
},'2000');