Search code examples
javascriptarraysnode.jsobjectpeer

How to store peer connections in array


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

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

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.

//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
}

Solution

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

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