基於第三方webrtc開源平台開發視頻會議難度不是很大,主要是業務方面的問題。但是,一旦涉及核心的底層問題就需要閱讀源代碼,找出bug了,難度不小。
項目需要,分析了一下peerconnection的創建過程。
假設clientA,clientB分為為offer和answer.
-
Offer端
pc =new RTCPeerConnection(null);
pc.onicecandidate=handleIceCandidate;
pc.onaddstream=handleRemoteStreamAdded;
pc.onremovestream=handleRemoteStreamRemoved;
pc.addStream(localStream);
pc.createOffer(setLocalAndSend,handleCreateOfferError);
function handleIceCandidate(event){
//將本地產生的candidate發送給對方
sendMessage({
type:”candidate”;
candidate:event.candidate.candidate;
……;
});
}
function setLocalAndSend(sdp){
pc.setLocalDescription(sdp);//設置本地sdp,完成設置后onicecandidate事件會調用。
sendMessage(sdp);//將offer發送給對方
}
當offer提供端接收到來自對方的answer時: pc.setRemoteDescription(new RTCSessionDescription(message));
當offer端接收到來自對方的candidate時,pc.addIceCandidate(candidate);//將來自對方的candidate設置給本地
2. Answer端的代碼與offer端類似,紅色部分代碼不同
pc =new RTCPeerConnection(null);
pc.onicecandidate=handleIceCandidate;
pc.onaddstream=handleRemoteStreamAdded;
pc.onremovestream=handleRemoteStreamRemoved;
pc.addStream(localStream);
注意區別:offer端是主動調用createOffer函數並將offer發送給對方。Answer端接受到offer后,才會創建peerConnection等一系列操作:
pc.setRemoteDescription(sdp);//設置接收到的遠端offer
pc.createAnswer(setLocalAndSend,null,sdpConstraints);//創建answer並發送給對方。
setLocalAndSend中會設置本地sdp,完成設置后onicecandidate事件會調用。然后將candidate發送給對方,對方收到candidate后調用addIceCandidate函數完成peerconnection的創建。
對於onaddstream事件的調用時機,對於offer端,在接收到offer之后就可能onaddstream事件就被觸發了。