为什么RTCPeerConnecting会永远保持“连接”状态?

时间:2019-08-31 19:10:14

标签: javascript webrtc

我正在尝试升级我的网络游戏以使用WebRTC不可靠的数据通道。

我的WebRTC连接静默失败。我之前有错误,但我已全部解决。但是,连接永远不会成功。

过去几天从事这项工作,从未建立联系。现在它默默地失败了。

//Signaling Code Setup

var configuration = {
        'iceServers': [{
                'url': 'stun:stun.l.google.com:19302'
        }]
};

var pc;
pc = new RTCPeerConnection(configuration);
pc.onicecandidate = function(candidate) {
  console.log("received ice candidate");
  console.log(candidate);
 socket.send(JSON.stringify({method: "ice candidate", candidate: candidate, enemy_name: enemy_name}));
}
pc.onnegotiationneeded = async () => {
try {
    console.log("negotiated needed. negotiating. (setting local description from created offer)");
    await pc.setLocalDescription(await pc.createOffer());
    // send the offer to the other peer
    socket.send(JSON.stringify({method: "SDP", desc: pc.localDescription, enemy_name: enemy_name}));
  } catch (err) {
    console.error(err);
  }
};

var dataChannelOptions = {
        ordered: false, //no guaranteed delivery, unreliable but faster
        maxRetransmits: 0
};

var dataChannel;

pc.onopen = function(event) {

  console.log("Peer channel opened.");

}

function joinReceived(){
    dataChannel = pc.createDataChannel('sendDataChannel');
    dataChannel.onopen = function(event) {
      console.log("Data channel opened.");
    }
}


async function onMessage(desc, candidate) {
  try {
    if (desc) {
      console.log(desc);
      // if we get an offer, we need to reply with an answer
      if (desc.type === 'offer') {
        console.log("setting remote description")
        await pc.setRemoteDescription(desc);
        console.log("setting local description from created answer")
        await pc.setLocalDescription(await pc.createAnswer());
        socket.send(JSON.stringify({method: "SDP", desc: pc.localDescription, enemy_name: enemy_name}));
      } else if (desc.type === 'answer') {
        console.log("setting remote description from answer")
        await pc.setRemoteDescription(desc);
      } else {
        console.log('Unsupported SDP type.');
      }
    } else if (candidate) {
      console.log("candidate received. adding. (addIceCandidate)")
      console.log(candidate);
      await pc.addIceCandidate(candidate);
    }
  } catch (err) {
    console.error(err);
  }
};
ws "/socket" do |socket, env|
  # sockets.push socket
  player_name = env.session.string("player_name")
  enemy_name = env.session.string("enemy_name") rescue "" # if we have this set in session, use it, or else set empty string
  sockets[player_name] = socket
  socket.on_message do |message|
    # handle incoming input
    json = JSON.parse(message)
    p json
    if json["method"] == "send_my_name" # allows us to set the name of our enemy after a join, so we can contact him using sockets
      # send name to enemy
      if json["enemy_name"].to_s != "" # its "" if we have no enemy
        enemy_name = json["name"].to_s
        sendname = {method: "send_my_name", enemy_name: enemy_name}.to_json
        # if sockets.has_key?(json["enemy_name"].to_s) # send enemy name to the player
        sockets[json["enemy_name"].to_s].send sendname
        # end
      end
    elsif json["method"] == "confirm_name"
      # set the enemy name in my sesson
      enemy_name = json["enemy_name"].to_s
      env.session.string("enemy_name", enemy_name)
      # send join to host (me)
      joined = {method: "joined", name: player_name, enemy_name: enemy_name}.to_json
      puts "player #{enemy_name} joined #{player_name}"
      if sockets.has_key?(player_name)
        sockets[player_name].send joined
      end
    elsif json["method"] == "move" # previously serverside game logic, ignore these statements

    elsif json["method"] == "rotate"

    elsif json["method"] == "ball"

    elsif json["method"] == "goal"

    elsif json["method"] == "SDP"
      # sdp offer, send to enemy
      puts "sending SDP #{json["desc"]["type"]} to #{json["enemy_name"].to_s}"
      if sockets.has_key?(json["enemy_name"].to_s)
        sockets[json["enemy_name"].to_s].send message
      end
    elsif json["method"] == "ice candidate"
      # ice
      puts "sending ICE candidate info to #{json["enemy_name"].to_s}"
      if sockets.has_key?(json["enemy_name"].to_s)
        sockets[json["enemy_name"].to_s].send message
      end
    end
  end
  socket.on_close do
    puts "Closing socket"
    matches.delete(player_name)
    matches.delete(enemy_name)
    sockets.delete(player_name)
    sockets.delete(enemy_name)
  end
end
    socket.onmessage = function(msg){
      console.log(msg); //Awesome!
      data = JSON.parse(msg.data);
      <% if enemy_name == "" %>
        let hosting = true;
      <% else %>
      // not redundant, new joined user won't have this set (they wont have gotten the first join)
        let hosting = false;
        enemy_name = "<%= enemy_name %>";
      <% end %>
      console.log(data); // which messages came in
      if(data.method == "joined" && data.name == localStorage.getItem("player_name")) {
        console.log("join received.")
        // join webRTC channel
        joinReceived();
        // a player has joined us, we're the enemy
        $("#enemy_name").html(data.enemy_name);
        enemy_name = data.enemy_name;
        score_1 = 0;
        score_1_text.text = localStorage.getItem("player_name") + ": " + score_1;
        score_2 = 0;
        score_2_text.text = enemy_name + ": " + score_2; // set enemy name in score board
      } else if (data.method == "goal" && data.name == enemy_name) {
      score_2 = score_2 + 1; // enemy scored (2 messages are generated?)
      score_2_text.text = enemy_name + ": " + score_2;
    } else if (data.method == "goal" && data.name == localStorage.getItem("player_name")) {
      score_1 = score_1 + 1; // we scored
      score_1_text.text = localStorage.getItem("player_name") + ": " + score_1;
    } else if (data.method == "SDP") {
      console.log("received session info from remote")
      onMessage(data.desc, null);
    } else if (data.method == "ice candidate") {
      console.log("received ice candidate from remote")
      onMessage(null, data.candidate.candidate);
    } else if (data.method == "send_my_name") {
      console.log("received enemy name");
      socket.send(JSON.stringify({method: "confirm_name", enemy_name: data.enemy_name}));
    }
  }

预期结果:RTCPeerConnection处于“已连接”状态,可以使用#send发送的2种方式dataChannel

0 个答案:

没有答案