PeerConnection

Example(摘)

 1 /*When two peers decide they are going to set up a connection to each other, they both go through these steps. The STUN/TURN server configuration describes a server they can use to get things like their public IP address or to set up NAT traversal. They also have to send data for the signaling channel to each other using the same out-of-band mechanism they used to establish that they were going to communicate in the first place.*/
 2 //假设信令通道存在
 3 var signalingChannel = createSignalingChannel();
 4 var pc;
 5 var configuration = ;
 6 
 7 //run start(true) to initial a call
 8 function start(isCaller){
 9     pc = new RTCPeerConnection(configuration);
10     
11     //send any ice candidates to the other peer
12     //ICE 交互式连接建立 NAT
13     pc.onicecandidate = function(evt){
14         signalingChannel.send(JSON.stringify({"candidate":evt.candidate}));
15     }
16     
17     //get the local stream,show it in the local video element and send it
18     navigator.getUserMedia({"audio":true,"video":true},function(stream){
19         selfView.src = URL.createObjectURL(stream);
20         pc.addStream(stream);
21         
22         if(isCaller)
23             pc.createOffer(gotDescription);
24         else
25             pc.createAnswer(pc.remoteDescription,gotDescription);
26         function gotDescription(desc){
27             pc.setLocalDescription(desc);
28             //trace("Offer from pc1 
"+desc.sdp);
29             //sdp : Session Description Protocol
30             signalingChannel.send(JSON.stringify({"sdp":desc}));
31         }
32     });
33 }
34 signalingChannel.onmessage = function(evt){
35     if(!pc)
36         start(false);
37     
38     var signal = JSON.parse(evt.data);
39     if(signal.sdp)
40         pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
41     else
42         pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
43 }
原文地址:https://www.cnblogs.com/sook/p/3155812.html