-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
具体代码请参考 omegle,Chrome 实测可运行
WebRTC 是一个支持P2P分享应用数据和进行电话会议的实时通信技术,
socket.io 基于 WebSocket 提供浏览器于服务器之间的全双工通信
信令服务器
信令是用来协调沟通的。 为了使WebRTC实现P2P的连接,WebRTC的客户端需要相互交换信息。
- Session control messages, 连接控制消息,用来打开通信或者中断通信
- Error messages, 发生错误时彼此告知的消息
- Media metadata, 媒体流元数据,例如带宽,媒体类型,发送/接收方的浏览器能够接受的编码器和分辨率
- Key data, 用来建立secure connections
- Network data, 例如公网中的IP地址和端口信息
offer, answer and candidate
RTCPeerConnection 是 WebRTC 应用用来传递元数据的API
本地媒体数据,例如分辨率,编码器和编码能力,这些元数据被用来供 offer 和 answer 使用
candidate 指的是 WebRTC 应用主机
Alice call Eve 的过程如下(必须先交换音视频信息,才会触发 icecandidate 事件):
取得本地流
- Alice 使用
navigator.webkitGetUserMedia方法获得本地流 - 将获取的 localMediaStream 通过
addStream方法添加到 RTCPeerConnection 需要发送的流
音视频设备信息交换
- Alice 创建 RTCPeerConnection 对象
- Alice 通过 RTCPeerConnection 的 createOffer 方法创建一个 offer (一个SDP Session Description 在 createOffer回调函数的参数中)
- Alice 传递 offer 到 setLocalDescription 方法
- Alice 用信令机制把 offer 送到 Eve
- Eve 执行 setRemoteDescription 处理 Alice 发过来的 offer,此时 Eve 的 RTCPeerConnection 就知道 Alice 的音视频信息了
- Eve 执行 createAnswer 方法,local session description: Eve's answer 会在其回调函数中
- Eve 将 Eve's answer 传递到 setLocalDescription 方法
- Eve 使用信令机制将 Eve's answer 传递给 Alice
- Alice 将 Eve's answer 作为 remote session description 传递给 setRemoteDescription 方法
+-----------+ 1. 发送 offer +------------+ 2. 转发Alice offer +-----------+
| | ----------------> | | ---------------> | |
| Alice | <--------------- | 信令服务器 | <-------------- | Eve |
| | 4. 转发Eve answer | | 3. 发送 answer | |
+-----------+ +------------+ +-----------+
网络信息交换
- Alice 创建 RTCPeerConnection 对象,[将 iceServer 的信息作为参数传入, 此时这个对象会自动向服务器询问自己的公网 IP 和端口]
- 为该 RTCPeerConnection 对象绑定 icecandidate 事件,该事件在 ICE Server 添加到 RTCPeerConnection 对象时触发(An icecandidate event is fired when an RTCIceCandidate has been added to the target)
- 在 icecandidate 事件中通过信令机制将 candidate(网络信息)传递给 Eve
- Eve 通过 addIceCandidate 方法保存 Alice 的网络信息
(用来NAT穿透,可以不需要)
+---------------+
| |
+-----------------> | STUN服务器 | <-------------+
| | | |
| +---------------+ |
| 询问外网IP和端口 询问外网IP和端口 |
| |
| |
+-----------+ 发送IP和端口 +------------+ 转发IP和端口 +-----------+
| | ----------> | | ----------> | |
| Alice | <---------- | 信令服务器 | <---------- | Eve |
| | 转发IP和端口 | | 发送IP和端口 | |
+-----------+ +------------+ +-----------+
要点
- 发送者,接收者需要区分好,前者发送 offer, 后者接收 offer,返还 answer
RTCPeerConnection.createOffer第三个参数接收options, 需要设置
options = {
offerToReceiveAudio: false, // 不接收音频
offerToReceiveVideo: true // 接收视频
}Metadata
Metadata
Assignees
Labels
No labels