Local:
Remote:
};//创建PeerConnection实例 (参数为null则没有iceserver,即使没有stunserver和turnserver,仍可在局域网下通讯)varpc=newwebkitRTCPeerConnection(iceServer);//发送ICE候选到其他客户端pc.onicecandidate=function(event){if(event.candidate!==null) {
socket.send(JSON.stringify({"event":"_ice_candidate","data": {"candidate": event.candidate
}
}));
}
};//如果检测到媒体流连接到本地,将其绑定到一个video标签上输出pc.onaddstream=function(event){
document.getElementById('remoteVideo').src=URL.createObjectURL(event.stream);
};//发送offer和answer的函数,发送本地session描述varsendOfferFn=function(desc){
pc.setLocalDescription(desc);
socket.send(JSON.stringify({"event":"_offer","data": {"sdp": desc
}
}));
},
sendAnswerFn=function(desc){
pc.setLocalDescription(desc);
socket.send(JSON.stringify({"event":"_answer","data": {"sdp": desc
}
}));
};//获取本地音频和视频流navigator.webkitGetUserMedia({"audio":true,"video":true},function(stream){//绑定本地媒体流到video标签用于输出document.getElementById('localVideo').src=URL.createObjectURL(stream);//向PeerConnection中加入需要发送的流pc.addStream(stream);//如果是发起方则发送一个offer信令if(isCaller){
pc.createOffer(sendOfferFn,function(error) {
console.log('Failure callback: '+error);
});
}
},function(error){//处理媒体流创建失败错误console.log('getUserMedia error: '+error);
});//处理到来的信令socket.onmessage=function(event){varjson=JSON.parse(event.data);
console.log('onmessage: ', json);//如果是一个ICE的候选,则将其加入到PeerConnection中,否则设定对方的session描述为传递过来的描述if( json.event==="_ice_candidate"){
pc.addIceCandidate(newRTCIceCandidate(json.data.candidate));
}else{
pc.setRemoteDescription(newRTCSessionDescription(json.data.sdp));//如果是一个offer,那么需要回复一个answerif(json.event==="_offer") {
pc.createAnswer(sendAnswerFn,function(error) {
console.log('Failure callback: '+error);
});
}
}
};