背景与价值DataChannel 支持可靠/不可靠与顺序/无序模式;对文件传输可结合分块与确认协议提升稳定性。基本连接async function setupPeer() { const pc = new RTCPeerConnection(); const dc = pc.createDataChannel('file', { ordered: true }); dc.onopen = () => console.log('dc-open'); dc.onmessage = (e) => handleMessage(e.data); const offer = await pc.createOffer(); await pc.setLocalDescription(offer); // 通过信令交换 SDP 与 ICE 后建立连接 return { pc, dc }; } 分块发送与确认function sendFile(dc: RTCDataChannel, buf: ArrayBuffer, chunkSize = 64 * 1024) { const u8 = new Uint8Array(buf); let offset = 0; let seq = 0; const sendChunk = () => { const end = Math.min(offset + chunkSize, u8.length); dc.send(JSON.stringify({ type: 'chunk', seq, data: Array.from(u8.slice(offset, end)) })); offset = end; seq++; if (offset < u8.length) setTimeout(sendChunk, 0); else dc.send(JSON.stringify({ type: 'end', total: seq })); }; sendChunk(); } 接收与重组const recv: Record<number, Uint8Array> = {}; let expected = 0; function handleMessage(raw: string) { const msg = JSON.parse(raw); if (msg.type === 'chunk') { recv[msg.seq] = new Uint8Array(msg.data); expected = Math.max(expected, msg.seq + 1); // 可选择发送 ack } else if (msg.type === 'end') { const total = msg.total; const out = new Uint8Array(Object.values(recv).reduce((a, b) => a + b.length, 0)); let off = 0; for (let i = 0; i < total; i++) { const c = recv[i]; out.set(c, off); off += c.length; } onFileComplete(new Blob([out])); } } 指标验证(Chrome 128/Edge 130)成功率:弱网下 ≥ 97%。吞吐:稳定在网络允许范围;分块提高健壮性。延迟:中等文件(10–50MB)传输端到端耗时可控;失败重试率 ≤ 3%。回退策略无法建立 P2P:回退到服务器中转或断点续传(TUS/Range)。测试清单大文件与弱网:分块与重组稳定;顺序与可靠模式可选。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.800139s