【WebRTC】WebRTC学习总结

来源 | 掘金 作者:Nirvana-cn
排版 | 前端时空

WebRTC (Web Real-Time Communications)

WebRTC 是一项「实时通讯技术」,它允许网络应用或者站点,在不借助中间媒介的情况下,建立浏览器之间点对点(Peer-to-Peer)的连接,实现视频流和(或)音频流或者其他任意数据的传输。WebRTC包含的这些标准使用户在无需安装任何插件或者第三方的软件的情况下,创建点对点(Peer-to-Peer)的数据分享和电话会议成为可能。本篇文章从自身实践出发,结合相关代码,总结WebRTC实现的基本流程。

1. 引言

首先我们先看《WebRTC权威指南》上给出的流程图,从这张图,我们要明确两件事:

  • 第一,通信双方需要先通过服务器交换一些信息

  • 第二,完成信息交换后,通信双方将直接进行连接以传输数据

然后我们再介绍一下WebRTC中的专有名词,方便读者对下文的理解。

  • RTCPeerConnection:核心对象,每一个连接对象都需要新建该对象

  • SDP(Session Description Protocol,会话描述协议):包含建立连接的一些必要信息,比如IP地址等,sdp由RTCPeerConnection对象方法创建,我们目前不需要知道该对象中的具体内容,使用黑盒传输即可

  • ICE(Interactive Connectivity Establishment,交互式连接建立技术):用户之间建立连接的方式,用来选取用户之间最佳的连接方式

2. WebRTC实现流程

以下代码不能直接运行,因为我这里并没有实现「信令服务器」,如何实现信令服务器可自由选择(比如,socket.io、websocket等)。首先发起方获取视频流,如果成功,则新建「RTCPeerConnection对象」,然后创建offer,并发送给应答方。

  • addStream方法将getUserMedia方法中获取的流(stream)添加到RTCPeerConnection对象中,以进行传输

  • onaddStream事件用来监听通道中新加入的流,通过e.stream获取

  • onicecandidate事件用来寻找合适的ICE

  • createOffer()是RTCPeerConnection对象自带的方法,用来创建offer,创建成功后调用setLocalDescription方法将localDescription设置为offer,localDescription即为我们需要发送给应答方的sdp

  • sendOffer和sendCandidate方法是自定义方法,用来将数据发送给服务器

// 引入<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>脚本
// 提升浏览器兼容性
var localConnection
var constraints={
    audio:false,
    video:true
}
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError)
function handleSuccess(stream) {
  document.getElementById("video").srcObject = stream
  localConnection=new RTCPeerConnection()
  localConnection.addStream(stream)
  localConnection.onaddstream=function(e) {
    console.log('获得应答方的视频流' + e.stream)
  }
  localConnection.onicecandidate=function(event){
    if(event.candidate){
        sendCandidate(event.candidate)
    }
  }
  localConnection.createOffer().then((offer)=>{
    localConnection.setLocalDescription(offer).then(sendOffer)
  })
}

同样的,接收方也需要新建一个RTCPeerConnection对象

var remoteConnection
var constraints={
    audio:false,
    video:true
    }
}
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError)
function handleSuccess(stream) {
  document.getElementById("video").srcObject = stream
  remoteConnection=new RTCPeerConnection()
  remoteConnection.addStream(stream)
  remoteConnection.onaddstream=function(e) {
    console.log('获得发起方的视频流' + e.stream)
  }
  remoteConnection.onicecandidate=function(event){
      if(event.candidate){
          sendCandidate(event.candidate)
      }
  }
}

当应答方收到发起方发送的offer之后,调用setRemoteDescription设置RTCPeerConnection对象的remoteDescription属性,设置成功之后调用createAnswer方法,创建answer成功之后将其设置为localDescription,然后把answer发送给服务器

let desc=new RTCSessionDescription(sdp)
remoteConnection.setRemoteDescription(desc).then(function() {
    remoteConnection.createAnswer().then((answer)=>{
        remoteConnection.setLocalDescription(answer).then(sendAnswer)
    })
})

当发起方收到应答方发送的answer之后,将其设置为remoteDescription,至此WebRTC连接完成。

let desc=new RTCSessionDescription(sdp)
localConnection.setRemoteDescription(desc).then(()=>{console.log('Peer Connection Success')})

此时虽然WebRTC连接已经完成,但是通信双方还不能直接通信,因为发送的ICE还没有处理,通信双方还没有确定最优的连接方式。应答方收到发起方发送的ICE数据时,调用RTCPeerConnection对象的addIceCandidate方法。remoteConnection.addIceCandidate(new RTCIceCandidate(ice))复制代码发起方收到应答方发送的ICE数据时,同样调用RTCPeerConnection对象的addIceCandidate方法。localConnection.addIceCandidate(new RTCIceCandidate(ice))

至此,一个最简单的WebRTC连接已经建立完成。

3. 数据通道

WebRTC擅长进行数据传输,不仅仅是音频和视频流,还包括我们希望的任何数据类型,相比于复杂的数据交换过程,创建一个数据通道这个主要功能已经在RTCDataConnection对象中实现了:

var peerConnection = new RTCPeerConnection();
var dataChannel = peerConnection.createDataChannel("label",dataChannelOptions);

WebRTC会处理好所有的事情,包括浏览器内部层。浏览器通过一系列的事件来通知应用程序,当前数据通道所处的状态。ondatachannel事件会通知RTCPeerConnection对象,RTCDataChannel对象本身在开启、关闭、发生错误或者接收到消息时会触发对应的事件。

dataChannel.onerror = function (error){
    console.log(error)
}

dataChannel.onmessage = function (event){
    console.log(event.data)
}

dataChannel.onopen = function (error){
    console.log('data channel opened')
    // 当创建一个数据通道后,你必须等onopen事件触发后才能发送消息
    dataChannel.send('Hello world')
}

dataChannel.onclose = function (error){
    console.log('data channel closed')
}

数据通道datachannel建立的过程略微不同于建立视频流或音频流双向连接,offer、answer、ice处理完毕之后,由一方发起请求即可。

localConnection = new RTCPeerConnection();

sendChannel = localConnection.createDataChannel("sendChannel");
sendChannel.onopen = handleSendChannelStatusChange;
sendChannel.onclose = handleSendChannelStatusChange;

接收方此时并不需要再次调用createDataChannel方法,只需要监听RTCPeerConnection实例对象上的ondatachannel事件就可以在回调中拿到发送方的请求,数据通道就建立起来了。

remoteConnection = new RTCPeerConnection();
remoteConnection.ondatachannel = receiveChannelCallback;

function receiveChannelCallback(event) {
    receiveChannel = event.channel;
    receiveChannel.onmessage = handleReceiveMessage;
    receiveChannel.onopen = handleReceiveChannelStatusChange;
    receiveChannel.onclose = handleReceiveChannelStatusChange;
  }

dataChannelOptions传入的配置项是可选的,并且是一个普通的JavaScript对象,这些配置项可以使应用在UDP或者TCP的优势之间进行变化。

  • reliable:设置消息是否进行担保

  • ordered:设置消息的接受是否需要按照发送时的顺序

  • maxRetransmitTime:设置消息发送失败时,多久重新发送

  • maxRetransmits:设置消息发送失败时,最多重发次数

  • protocol:设置强制使用其他子协议,但当用户代理不支持该协议时会报错

  • negotiated:设置开发人员是否有责任在两边创建数据通道,还是浏览器自动完成这个步骤

  • id:设置通道的唯一标识

4. 文件共享

目前,数据通道支持如下类型:

  • String:JavaScript基本的字符串

  • Blob(binary large object):二进制大对象

  • ArrayBuffer:确定数组长度的数据类型

  • ArrayBufferView:基础的数组视图

其中,Blob类型是一个可以存储二进制文件的容器,结合HTML5相关文件读取API,可以实现文件共享的功能。

本文来源于网络,已注明原创作者及来源。如有侵权请联系删除。

END

了解更多

点击下方图片即可阅读

CSS + JS 送学妹满屏幕小爱心

200行JS代码,带你实现代码编译器(人人都能学会)

JS自定义事件如此简单!

Webpack插件开发如此简单

个人博客:http://www.pingan8787.com 微信公众号【前端自习课】和千万网友一起,每日清晨,享受一篇前端优秀文章。 目前已连续推送文章 600+ 天,愿每个人的初心都能一直坚持下去!
原文地址:https://www.cnblogs.com/pingan8787/p/13069390.html