RTCPeerConnection 是 WebRTC API 中的中心接口。它表示本地和远程对等之间的连接,并提供建立连接所需的所有函数和事件。
建立对等连接
实现 WebRTC 功能的应用通常会严重依赖 RTCPeerConnection 接口。从调用方(即发起连接的对等方)的角度来看,建立连接的过程通常如下:
- 使用适当的 ICE 配置创建新的 RTCPeerConnection实例。
- 使用 RTCPeerConnection.createOffer()创建本地 SDP 描述。
- 使用 RTCPeerConnection.setLocalDescription()设置本地 SDP 描述。
- 将本地 SDP 描述传输(使用信令服务)到远程对等方。
- 为 RTCPeerConnection上的icecandidate事件注册监听器。
- 对于每个 icecandidate事件,请使用信号服务将其传输到远程对等方。
- 等待来自信令服务的传入远程 SDP 描述,并使用 RTCPeerConnection.setRemoteDescription()进行设置。
- 等待来自信号服务的传入远程 ICE 候选,并使用 RTCPeerConnection.addIceCandidate()将其添加
在被调用方,该过程略有不同。
- 使用适当的 ICE 配置创建新的 RTCPeerConnection实例。
- 等待来自信令服务的传入远程 SDP 描述,并使用 RTCPeerConnection.setRemoteDescription()进行设置。
- 通过调用 RTCPeerConnection.createAnswer()为远程 SDP 描述创建回答。
- 将答案转移(使用信令服务)到远程对等方。
- 为 RTCPeerConnection上的icecandidate事件注册监听器。
- 对于每个 icecandidate事件,请使用信号服务将其传输到远程对等方。
- 等待来自信号服务的传入远程 ICE 候选,并使用 RTCPeerConnection.addIceCandidate()将其添加
此 API 的难点在于,其中大多数操作都是异步的,这通常会使 WebRTC 应用的实际实现变得复杂。许多函数都会返回 Promise,必须先解析此值,才能继续执行流程中的下一步。
建议开发者在使用此 API 实现应用时,使用 async 和 await 而不是注册监听器(使用 Promise.then()),因为这样可以使代码更易于理解。请考虑以下示例:
function createAndSendOffer(peerConnection, signallingService) {
    peerConnection.createOffer()
                  .then(offer => {
                      signallingService.send({
                          type: 'offer',
                          data: offer
                      });
                  });
}
使用 async 和 await 编写上述代码时,我们会得到以下结果:
async function createAndSendOffer(peerConnection, signallingService) {
    const offer = await peerConnection.createOffer();
    signallingService.send({
        type: 'offer',
        data: offer
    });
}