WebRTC 实时音视频与数据通道实践概述WebRTC 提供浏览器原生的音视频与数据通道能力。本文通过稳定 API 展示基本连接流程:媒体采集、信令交换、ICE 候选与数据通道。媒体采集const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }) videoEl.srcObject = stream 点对点连接与信令const pc = new RTCPeerConnection() stream.getTracks().forEach(t => pc.addTrack(t, stream)) pc.onicecandidate = e => { if (e.candidate) sendToServer({ type: 'candidate', candidate: e.candidate }) } const offer = await pc.createOffer() await pc.setLocalDescription(offer) sendToServer({ type: 'offer', sdp: offer.sdp }) // 远端:收到 offer 后创建 answer 并返回;本端设置远端描述 await pc.setRemoteDescription({ type: 'answer', sdp: remoteAnswerSdp }) 数据通道const dc = pc.createDataChannel('chat') dc.onopen = () => dc.send('hello') dc.onmessage = e => console.log('msg:', e.data) 验证要点示例基于稳定浏览器 API;需配合后端信令服务转发 `offer/answer/ICE`。在网络面板与日志中观察候选收集与连接状态(`connectionstatechange`)。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
2.020241s