|
基于第三方webrtc开源平台开发视频会议难度不是很大,主要是业务方面的问题。但是,一旦涉及核心的底层问题就需要阅读源代码,找出bug了,难度不小。 项目需要,分析了一下peerconnection的创建过程。 假设clientA,clientB分为为offer和answer.
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事件就被触发了。
|