答案:通过RTCPeerConnection API实现浏览器点对点通信,需创建连接实例、配置STUN服务器、交换SDP和ICE候选信息。发起方创建offer,接收方回应answer,双方通过信令通道传输连接数据,建立P2P连接后可传输音视频或文本。需在HTTPS或localhost环境下运行,结合WebSocket等实现信令交互。

要通过 JavaScript 的 WebRTC 实现浏览器端的点对点通信,核心是利用 RTCPeerConnection API 建立两个浏览器之间的直接连接。整个过程不依赖中间服务器传输音视频流,但需要信令机制交换连接信息。
WebRTC 本身不提供信令(signaling),你需要用 WebSocket、HTTP 或其他方式传递会话描述(SDP)和网络候选(ICE candidates)。关键步骤包括:
每个端都需要初始化一个 RTCPeerConnection,并配置 ICE 服务器(如 STUN/TURN),帮助穿透 NAT 和防火墙:
const configuration = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] // 免费 STUN 服务器 }; const pc = new RTCPeerConnection(configuration); // 监听 ICE 候选信息,通过信令通道发送给对方 pc.onicecandidate = event => { if (event.candidate) { signalingChannel.send({ candidate: event.candidate }); } }; // 接收远程流(例如对方摄像头) pc.ontrack = event => { const remoteVideo = document.getElementById('remoteVideo'); remoteVideo.srcObject = event.streams[0]; };主动发起方(caller)需要创建 offer,设置本地描述,并发送给接收方:
立即学习“Java免费学习笔记(深入)”;
async function createOffer(pc) { const offer = await pc.createOffer(); await pc.setLocalDescription(offer); // 通过信令通道发送 offer 给对方 signalingChannel.send({ offer: pc.localDescription }); }接收方收到 offer 后,设置远程描述,创建 answer 并返回:
signalingChannel.onmessage = async (event) => { const message = event.data; if (message.offer) { await pc.setRemoteDescription(new RTCSessionDescription(message.offer)); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); signalingChannel.send({ answer: pc.localDescription }); } if (message.answer) { await pc.setRemoteDescription(new RTCSessionDescription(message.answer)); } if (message.candidate) { pc.addIceCandidate(new RTCIceCandidate(message.candidate)); } };你可以发送摄像头视频,也可以使用 RTCDataChannel 传文本或文件:
// 发送数据示例 const dataChannel = pc.createDataChannel("chat"); dataChannel.onopen = () => dataChannel.send("Hello P2P!"); dataChannel.onmessage = event => console.log("收到:", event.data); // 接收方监听数据通道 pc.ondatachannel = event => { const receiveChannel = event.channel; receiveChannel.onmessage = event => console.log("数据:", event.data); }; // 添加本地视频流 navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(stream => { document.getElementById('localVideo').srcObject = stream; stream.getTracks().forEach(track => pc.addTrack(track, stream)); });基本上就这些。只要信令通了,两个浏览器就能建立直接连接。注意:必须在 HTTPS 或 localhost 下运行,因为 WebRTC 涉及用户媒体权限。实际部署时可结合 WebSocket 搭建信令服务器,实现多用户通信。不复杂但容易忽略细节,比如 ICE 候选是否完整、SDP 设置顺序等。
以上就是怎样通过 JavaScript 的 WebRTC 实现浏览器端的点对点通信?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号