wangpin34 / blog

个人博客, 博文写在 Issues 里

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

WebRTC 建立连接的过程

wangpin34 opened this issue · comments

commented

WebRTC 帮助浏览器建议点对点的连接,并可以在连接之上搭建数据通道和流媒体通道,以完成复杂的通信过程。

两个客户端 pc1 和 pc2 建立连接需要的条件。

  • 都能访问 stun 服务器

连接过程中需要的关键元素。

  • offer 和 answer
  • candidate

建立连接的过程(pc1 主动连接 pc2)

Offer 和 answer

  • pc1 和 pc2 分别创建连接对象
var pc1 = new RTCPeerConnection(servers, pcConstraint);
var pc2 = new RTCPeerConnection(servers, pcConstraint);
  • pc1 创建 offer,通过服务器转交给 pc2
pc1.createOffer().then(function(offer) { 
  pc1.setLocalDescription(offer);
  sendToServer(offer);
})
  • pc2 收到 offer,设置为 remote desc,同时创建 answer,通过服务器转交给 pc1
pc2.setRemoteDescription(offer);
pc2.createAnswer().then(function(answer) { 
  pc2.setLocalDescription(answer);
  sendToServer(answer);
})
  • pc1 收到 answer,设置为 remote desc
pc1.setRemoteDescription(answer);

Candidate

Candidate 的交换比较简单,pc1 和 pc2 分别获取自己的 Candidate, 通过服务器交换,然后添加到候选列表

pc1.addIceCandidate(new RTCIceCandidate(pc2Candidate));

pc2.addIceCandidate(new RTCIceCandidate(pc1Candidate));

Stream 和 dataChannel

待补充。

Stream 和 dataChannel

浏览器提供了getUserMedia 方法来获得MediaStream

navigator.mediaDevices.getUserMedia({video:true, audio:true})
        .then((stream) => {
          /* use the stream */
});

pc2作为stream的接收方需要提前监听onaddstream事件

pc2.onaddstream = function(event) {
    var stream = event.stream;
    ...
}

在pc1通过getUserMedia获得stream之后将它添加到连接里

pc1.addStream(stream);

接下来pc1和pc2做negotiation(交换offer, answer和candidate)。完成后会触发pc2的onaddstream完成sream的传送。

如果pc1.addStream(stream)发生在negotiation之后需要renegotiation。