为什么不“onicecandidate”工作?

时间:2013-03-18 18:59:34

标签: javascript webrtc stun

我无法通过它的PeerConnection和'onicecandidate'事件了解webRTC。

据我了解,您必须使用STUN(或TURN)服务器启动对等连接,因为它会将您的ICE候选人发回给与另一个对等方进行通信。

我已经看到了将PeerConnection对象的服务器参数留下的示例,我也不明白,但我们只是说它确实需要服务器参数。

所以,当我写下以下代码时:

    var pc, ice = { "iceServers": [{ "url": "stun:stun.l.google.com:19302" }] };
if(typeof mozRTCPeerConnection === 'function') {

    pc = new mozRTCPeerConnection(ice);
}
else {
    console.log('google');
    pc = new webkitRTCPeerConnection(ice);
}


pc.onicecandidate  = function(event) { 
    console.log(event);
}

我希望'onicecandidate'事件会触发,但它不起作用。我也尝试过其他公共STUN服务器,但没有任何反应。所以我认为我的理解可能有些问题:)

1 个答案:

答案 0 :(得分:24)

在调用setLocalDescription()之前,PeerConnection不会开始收集候选者;提供给setLocalDescription的信息告诉PeerConnection需要收集多少候选人。 (setLocalDescription的此行为在其http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-03#section-4.2.4

的定义中指出

以下是在同一浏览器窗口中建立两个PeerConnections之间的连接的完整流程(添加MediaStreams以忽略信号):

var pc1, pc2, offer, answer;

pc1 = new webkitRTCPeerConnection(options);
pc2 = new webkitRTCPeerConnection(options);

pc1.onicecandidate = function(candidate) {
  pc2.addIceCandidate(candidate);
};

pc2.onicecandidate = function(candidate) {
  pc1.addIceCandidate(candidate);
};

pc1.createOffer(onOfferCreated, onError);

function onError(err) {
  window.alert(err.message);
}

function onOfferCreated(description) {
  offer = description;
  pc1.setLocalDescription(offer, onPc1LocalDescriptionSet, onError);
}

function onPc1LocalDescriptionSet() {
  // after this function returns, pc1 will start firing icecandidate events
  pc2.setRemoteDescription(offer, onPc2RemoteDescriptionSet, onError);
}

function onPc2RemoteDescriptionSet() {
  pc2.createAnswer(onAnswerCreated, onError);
}

function onAnswerCreated(description) {
  answer = description;
  pc2.setLocalDescription(answer, onPc2LocalDescriptionSet, onError);
}

function onPc2LocalDescriptionSet() {
  // after this function returns, you'll start getting icecandidate events on pc2
  pc1.setRemoteDescription(answer, onPc1RemoteDescriptionSet, onError);
}

function onPc1RemoteDescriptionSet() {
  window.alert('Yay, we finished signaling offers and answers');
}

由于您在问题中包含了mozPeerConnection,我会注意到Firefox目前不会生成“涓流候选人”。这意味着它将在候选/答案中将其候选地址包含为“c”行,并且永远不会调用onicecandidate回调。

这种方法的缺点是Firefox必须等待所有候选者在创建其提议/答案之前被收集(这个过程可能涉及联系STUN和TURN服务器并等待响应或请求超时)