WebRTC 受到主流网络浏览器的支持,包括 Google Chrome、Mozilla Firefox、Safari 和 Microsoft Edge。WebRTC 之所以受到广泛采用,是因为其开源特性、易于实现,而且无需第三方插件即可构建无缝实时通讯应用程序。
2. 了解须要的 WebRTC API
要利用 WebRTC(Web 实时通讯),您需要熟悉促进 Web 浏览器之间实时通讯所需的 API 和库。WebRTC 可直接在 Web 应用程序内实现点对点音频、视频和数据传播输,使其成为构建视频集会、语音通话和其他实时通讯功能的理想选择。以下是您应该了解的根本组件:
2.1 getUserMedia API(获取用户媒体)
该API可以访问用户的媒体装备(摄像头和麦克风),并提供可与RTCPeerConnection一起利用的MediaStream对象。
2.2 RTCPeerConnection API
该 API 是 WebRTC 的焦点,负责建立和管理浏览器之间的点对点连接。它处置处罚 ICE(交互式连接建立)协商、NAT 遍历和媒体传播输。
2.3 RTCDataChannel API
此 API 提供无需服务器的点对点数据通讯功能。它可用于在对等点之间发送恣意数据。
2.4 Signaling(信令)
WebRTC 需要在建立直接连接之前通过信令在对等端之间互换连接详细信息。此过程不是由 WebRTC 标准定义的,需要单独的信令机制,例如 WebSocket 或服务器端应用程序。
2.5 其他 WebRTC API
在我的网页示例中,我将利用 Ant Design 作为 UI 库,以使我的生活更轻松。编辑后,我的 React 页面将如下所示:
import React from 'react';
import {Button, Typography, Input} from 'antd';
import '../App.css';
const {Title, Paragraph} = Typography;
const {TextArea} = Input;
function App() {
const renderHelper = () => {
return (
<div className="wrapper">
<Input
placeholder="User ID"
style={{width: 240, marginTop: 16}}
/>
<Input
placeholder="Channel Name"
style={{width: 240, marginTop: 16}}
/>
<Button
style={{width: 240, marginTop: 16}}
type="primary"
>
Call
</Button>
<Button
danger
style={{width: 240, marginTop: 16}}
type="primary"
>
Hangup
</Button>
</div>
);
};
const renderTextarea = () => {
return (
<div className="wrapper">
<TextArea
style={{width: 240, marginTop: 16}}
placeholder='Send message'
/>
<TextArea
style={{width: 240, marginTop: 16}}
placeholder='Receive message'
disabled
/>
<Button
style={{width: 240, marginTop: 16}}
type="primary"
disabled={sendButtonDisabled}
>
Send Message
</Button>
</div>
);
};
return (
<div className="App">
<div className="App-header">
<Title>WebRTC</Title>
<Paragraph>This is a simple demo app that demonstrates how to build a WebRTC application from scratch, including a signaling server. It serves as a step-by-step guide to help you understand the process of implementing WebRTC in your own projects.</Paragraph>