Page 296 - Web性能权威指南
P. 296

每发现一个新候选项(一个 IP 加一个端口号),代理就会自动通过 RTCPeerConnection
               对象注册它,并通过一个回调函数(onicecandidate)通知应用。ICE 在完成收集工
               作后,也会再触发同一个回调函数,以通知应用。下面我们就来看一看 ICE 在前面
               的例子中所扮演的角色:

                   var ice = {"iceServers": [
                                 {"url": "stun:stun.l.google.com:19302"}, ➊
                                 {"url": "turn:user@turnserver.com", "credential": "pass"} ➋
                             ]};
                   var signalingChannel = new SignalingChannel();
                   var pc = new RTCPeerConnection(ice);
                   navigator.getUserMedia({ "audio": true }, gotStream, logError);

                   function gotStream(stream) {
                     pc.addstream(stream);
                     pc.createOffer(function(offer) {
                       pc.setLocalDescription(offer); ➌
                     });
                   }

                   pc.onicecandidate = function(evt) {
                     if (evt.target.iceGatheringState == "complete") { ➍
                         local.createOffer(function(offer) {
                           console.log("Offer with ICE candidates: " + offer.sdp);
                           signalingChannel.send(offer.sdp); ➎
                         });
                     }
                   }
                   ...
                   // 包含 ICE 候选项的提议:
                   // a=candidate:1862263974 1 udp 2113937151 192.168.1.73 60834 typ host ... ➏
                   // a=candidate:2565840242 1 udp 1845501695 50.76.44.100 60834 typ srflx ... ➐

               ➊ STUN 服务器,配置为使用谷歌的公共测试服务器
               ➋ TURN 服务器,用于端到端连接失败时转发数据
               ➌ 应用本地会话描述:初始化 ICE 收集过程
               ➍ 预订 ICE 事件,监听 ICE 收集完成
               ➎ 生成 SDP 提议(此时包含发现的 ICE 候选项)
               ➏ 本地端的私有 ICE 候选项(192.168.1.73:60834)
               ➐ STUN 服务器返回的公有 ICE 候选项(50.76.44.100:69834)








               286   |   第 18 章
   291   292   293   294   295   296   297   298   299   300   301