PeerConnection

时间:2021-05-12 22:11:20

Example(摘)

 /*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.*/
//假设信令通道存在
var signalingChannel = createSignalingChannel();
var pc;
var configuration = ; //run start(true) to initial a call
function start(isCaller){
pc = new RTCPeerConnection(configuration); //send any ice candidates to the other peer
//ICE 交互式连接建立 NAT
pc.onicecandidate = function(evt){
signalingChannel.send(JSON.stringify({"candidate":evt.candidate}));
} //get the local stream,show it in the local video element and send it
navigator.getUserMedia({"audio":true,"video":true},function(stream){
selfView.src = URL.createObjectURL(stream);
pc.addStream(stream); if(isCaller)
pc.createOffer(gotDescription);
else
pc.createAnswer(pc.remoteDescription,gotDescription);
function gotDescription(desc){
pc.setLocalDescription(desc);
//trace("Offer from pc1 \n"+desc.sdp);
//sdp : Session Description Protocol
signalingChannel.send(JSON.stringify({"sdp":desc}));
}
});
}
signalingChannel.onmessage = function(evt){
if(!pc)
start(false); var signal = JSON.parse(evt.data);
if(signal.sdp)
pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
else
pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
}