当前位置:网站首页>【山大会议】WebRTC基础之对等体连接
【山大会议】WebRTC基础之对等体连接
2022-06-22 14:41:00 【小栗帽今天吃什么】
文章目录
前言
在上一篇文章中,我们简单介绍了一下如何通过 WebRTC 提供的 API 实现用户设备媒体流的获取。在这篇文章中,我将着重介绍如何使用 WebRTC 搭建一个简单的 WebRTC 一对一音视频通话的 Demo。
UI 搭建
首先,我们先编写我们的 HTML 代码,搭好页面的骨架。
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>简单的WebRTC测试</title>
<style> * {
margin: 0%; padding: 0%; } #btn {
font-size: 3rem; } #room {
width: 100vw; height: 100vh; } video {
width: 480px; height: 270px; background: black; } </style>
</head>
<body>
<div id="room">
<video id="local" muted></video>
<video id="remote"></video>
<div>
<textarea id="localSDP" cols="30" rows="10" placeholder="我的SDP" disabled ></textarea>
<textarea id="remoteSDP" cols="30" rows="10" placeholder="对方SDP" disabled ></textarea>
<br />
<button id="ready">获取媒体</button>
<button id="send" disabled>发起会话</button>
</div>
</div>
</body>
</html>
我们搭建了一个简单的页面骨架,两个 <video /> 标签分别对应自己发出的视频流以及对方发送给自己的视频流。两个 <textarea /> 分别存储双方的 SDP 。
script 编写
在搭建好骨架后,我们来编写具体的逻辑。
获取媒体流
首先,我们需要点击 id 为 ready 的按钮,获取用户本地的音视频流。代码如下:
let localStream;
document.querySelector('#ready').onclick = () => {
navigator.mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then((stream) => {
document.querySelector('#ready').disabled = true;
localStream = stream;
document.querySelector('#local').srcObject = localStream;
document.querySelector('#local').play();
document.querySelector('#send').disabled = false;
});
};
建立本地通信信道
由于我们这个 Demo 是建立于两个不同的标签页中的,因此我们需要一个机制能在两个标签页中进行通信。在生产环境中,我们可以依赖于后端所搭建的 WebSocket 进行不同客户端间的通信,而在本地的开发环境中,我们可以选择使用 BroadcastChannel 对象来实现不同标签页之间的通信。
const bc = new BroadcastChannel('webrtc');
bc.onmessage = (e) => {
switch (e.data.type) {
case 'offer':
sendAnswer(e.data.sdp);
break;
case 'answer':
recvAnswer(e.data.sdp);
break;
case 'candidate':
handleCandidate(e.data);
break;
}
};
编写对等体连接代码
下面来到我们的核心部分,对对等体的逻辑进行设计。首先,我们先定义一个 RTCPeerConnection 对象:
const peer = new RTCPeerConnection({
// iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }],
});
事件监听
创建好对等体连接对象后,我们为对等体连接监听两个事件。
ICE候选者
首先是监听 ICE 候选者,当监听到该事件时,我们使用 BroadcastChannel 对象将候选者数据传送给对方。
peer.onicecandidate = (evt) => {
const message = {
type: 'candidate',
candidate: null,
};
if (evt.candidate) {
message.candidate = evt.candidate.candidate;
message.sdpMid = evt.candidate.sdpMid;
message.sdpMLineIndex = evt.candidate.sdpMLineIndex;
}
bc.postMessage(message);
};
远程轨道改变
监听该事件可以帮助我们知晓对方是否有向对等连接添加新的流轨道,我们可以将该流轨道展示在我们的界面中。
peer.ontrack = (e) => {
const video = document.querySelector('#remote');
if (video.srcObject !== e.streams[0]) {
video.srcObject = e.streams[0];
console.log('pc received remote stream');
video.play();
}
};
RTCPeerConnection 生命周期
下面我们来实现整个连接的不同生命周期的处理代码。
发送 Offer
连接的建立过程是一个两次握手的机制,首先由发起方发送一条 Offer 信息。
document.querySelector('#send').onclick = sendOffer;
function sendOffer() {
peer.createOffer({
mandatory: {
OfferToReceiveAudio: true, // 如果该值为false,即使本地端将发送音频数据,也不会提供远程端点发送音频数据。 如果此值为true,即使本地端不会发送音频数据,也将向远程端点发送音频数据。默认行为是仅在本地发送音频时才提供接收音频,否则不提供。
OfferToReceiveVideo: true,
},
}).then((sdp) => {
peer.setLocalDescription(sdp);
document.querySelector('#localSDP').value = sdp.sdp;
document.querySelector('#send').disabled = false;
bc.postMessage({
type: 'offer',
sdp: sdp.sdp,
});
});
}
响应 Offer
接到 Offer 请求的被呼叫方,将响应此 Offer,并创建 Answer:
function sendAnswer(remoteSDP) {
document.querySelector('#remoteSDP').value = remoteSDP;
peer.setRemoteDescription(
new RTCSessionDescription({
sdp: remoteSDP,
type: 'offer',
})
);
peer.createAnswer({
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true,
},
}).then((sdp) => {
peer.setLocalDescription(sdp);
document.querySelector('#send').disabled = false;
document.querySelector('#localSDP').value = sdp.sdp;
bc.postMessage({
type: 'answer',
sdp: sdp.sdp,
});
});
}
接收 Answer
最后由发起方接收 Answer 并设置远程 SDP 。
function recvAnswer(remoteSDP) {
document.querySelector('#remoteSDP').value = remoteSDP;
peer.setRemoteDescription(
new RTCSessionDescription({
sdp: remoteSDP,
type: 'answer',
})
);
}
候选者的处理
之前我们监听了 ICE 候选者改变的事件,并将候选者数据发送给了对方,下面我们将完善接到候选者数据后的操作。
function handleCandidate(data) {
if (data.candidate) {
const {
candidate, sdpMLineIndex, sdpMid } = data;
peer.addIceCandidate(data)
.then((pc) => {
console.log(`addIceCandidate success`);
})
.catch((pc, err) => {
console.log(`failed to add ICE Candidate: ${
err.toString()}`);
});
}
}
以上便是整个对等体连接的全过程,
示例地址:简单的WebRTC示例,打开两个标签页使用
完整的代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>简单的WebRTC测试</title>
<style> * {
margin: 0%; padding: 0%; } #btn {
font-size: 3rem; } #room {
width: 100vw; height: 100vh; } video {
width: 480px; height: 270px; background: black; } </style>
</head>
<body>
<div id="room">
<video id="local" muted></video>
<video id="remote"></video>
<div>
<textarea id="localSDP" cols="30" rows="10" placeholder="我的SDP" disabled ></textarea>
<textarea id="remoteSDP" cols="30" rows="10" placeholder="对方SDP" disabled ></textarea>
<br />
<button id="ready">获取媒体</button>
<button id="send" disabled>发起会话</button>
</div>
</div>
<script> const bc = new BroadcastChannel('webrtc'); bc.onmessage = (e) => {
switch (e.data.type) {
case 'offer': sendAnswer(e.data.sdp); break; case 'answer': recvAnswer(e.data.sdp); break; case 'candidate': handleCandidate(e.data); break; } }; document.querySelector('#ready').onclick = () => {
navigator.mediaDevices .getUserMedia({
video: true, audio: true, }) .then((stream) => {
document.querySelector('#ready').disabled = true; localStream = stream; document.querySelector('#local').srcObject = localStream; document.querySelector('#local').play(); document.querySelector('#send').disabled = false; document.querySelector('#send').onclick = sendOffer; for (const track of localStream.getTracks()) {
peer.addTrack(track, localStream); } }); }; const peer = new RTCPeerConnection({
// iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }], }); peer.onicecandidate = (evt) => {
const message = {
type: 'candidate', candidate: null, }; if (evt.candidate) {
message.candidate = evt.candidate.candidate; message.sdpMid = evt.candidate.sdpMid; message.sdpMLineIndex = evt.candidate.sdpMLineIndex; } bc.postMessage(message); }; peer.ontrack = (e) => {
const video = document.querySelector('#remote'); if (video.srcObject !== e.streams[0]) {
video.srcObject = e.streams[0]; console.log('pc received remote stream'); video.play(); } }; function sendOffer() {
peer.createOffer({
mandatory: {
OfferToReceiveAudio: true, // 如果该值为false,即使本地端将发送音频数据,也不会提供远程端点发送音频数据。 如果此值为true,即使本地端不会发送音频数据,也将向远程端点发送音频数据。默认行为是仅在本地发送音频时才提供接收音频,否则不提供。 OfferToReceiveVideo: true, }, }).then((sdp) => {
peer.setLocalDescription(sdp); document.querySelector('#localSDP').value = sdp.sdp; document.querySelector('#send').disabled = false; bc.postMessage({
type: 'offer', sdp: sdp.sdp, }); }); } function sendAnswer(remoteSDP) {
document.querySelector('#remoteSDP').value = remoteSDP; peer.setRemoteDescription( new RTCSessionDescription({
sdp: remoteSDP, type: 'offer', }) ); peer.createAnswer({
mandatory: {
OfferToReceiveAudio: true, OfferToReceiveVideo: true, }, }).then((sdp) => {
peer.setLocalDescription(sdp); document.querySelector('#send').disabled = false; document.querySelector('#localSDP').value = sdp.sdp; bc.postMessage({
type: 'answer', sdp: sdp.sdp, }); }); } function recvAnswer(remoteSDP) {
document.querySelector('#remoteSDP').value = remoteSDP; peer.setRemoteDescription( new RTCSessionDescription({
sdp: remoteSDP, type: 'answer', }) ); } function handleCandidate(data) {
if (data.candidate) {
const {
candidate, sdpMLineIndex, sdpMid } = data; peer.addIceCandidate(data) .then((pc) => {
console.log(`addIceCandidate success`); }) .catch((pc, err) => {
console.log(`failed to add ICE Candidate: ${
err.toString()}`); }); } } </script>
</body>
</html>
边栏推荐
- 向量6(继承)
- Cve-2022-0847 (privilege lifting kernel vulnerability)
- 大佬们好,初次使用MySQL cdc 报错
- 模板特例化 template<>
- A simple understanding of hill ordering
- 【题目精刷】2023禾赛-FPGA
- "Software defines the world, open source builds the future" 2022 open atom global open source summit will open at the end of July
- On the routing tree of gin
- High precision calculation
- The MIHA tour club in June is hot! 500+ posts, more than HC, just this summer (with internal promotion method)
猜你喜欢

FPGA collects DHT11 temperature and humidity

Bridging the gap between open source databases and database services
![[Shangshui Shuo series] day three - VIDEO](/img/42/0911fee2a36f6dda345a571a31acd5.png)
[Shangshui Shuo series] day three - VIDEO

Hongshi electric appliance rushes to the Growth Enterprise Market: the annual revenue is 600million yuan. Liujinxian's equity was frozen by Guangde small loan

Scala language learning-05-a comparison of the efficiency of recursion and tail recursion
The MIHA tour club in June is hot! 500+ posts, more than HC, just this summer (with internal promotion method)

标准化、最值归一化、均值归一化应用场景的进阶思考

UK considers listing arm in London based on national security

#进程地址空间

pymssql模块使用指南
随机推荐
Trust level of discover
UK considers listing arm in London based on national security
Ask if you want to get the start of sqlserver_ Is there a good way for LSN?
Quick sort_ sort
Batch export excel zip using zipfile, openpyxl and flask
The IPO of Tian'an technology was terminated: Fosun and Jiuding were shareholders who planned to raise 350million yuan
TDengine 连接器上线 Google Data Studio 应用商店
Quickly play ci/cd graphical choreography
uni开发微信小程序自定义相机自动检测(人像+身份证)
SDVO:LDSO+语义,直接法语义SLAM(RAL 2022)
FPGA collects DHT11 temperature and humidity
How to use the concat() function of MySQL
华为机器学习服务银行卡识别功能,一键实现银行卡识别与绑定
2020年蓝桥杯省赛真题-走方格(DP/DFS)
天安科技IPO被终止:曾拟募资3.5亿 复星与九鼎是股东
『忘了再学』Shell流程控制 — 38、while循环和until循环介绍
Self inspection is recommended! The transaction caused by MySQL driver bug is not rolled back. Maybe you are facing this risk!
对领域驱动设计DDD理解
大佬们好,初次使用MySQL cdc 报错
Navicat Premium 连接Oracle 数据库(图文教程)