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
}
听起来像'current_player'不是一个有效的引用。你在检查它的价值吗? – mscdex
是的。我能够控制台登录当前播放器#@mscdex –
如果你使用'console.dir(Object.keys(connections))',它是否显示(第一次)超时回调的current_player中包含的键? – mscdex