概述DataChannel 适合点对点分块传输。本文提供接收端的重组、校验与进度持久化方案。能力与接收重组function supportsRTC() { return typeof RTCPeerConnection === 'function'; } function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; if (!db.objectStoreNames.contains('rx')) db.createObjectStore('rx'); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); } async function saveChunk(name, idx, bytes) { const db = await openDB('dc-rx'); const tx = db.transaction('rx','readwrite'); tx.objectStore('rx').put(bytes, `${name}:${idx}`); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); } async function saveProgress(name, idx) { const db = await openDB('dc-rx'); const tx = db.transaction('rx','readwrite'); tx.objectStore('rx').put(idx, `${name}:progress`); await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); }); db.close(); } async function loadProgress(name) { const db = await openDB('dc-rx'); const tx = db.transaction('rx','readonly'); const req = tx.objectStore('rx').get(`${name}:progress`); const v = await new Promise((res, rej) => { req.onsuccess = () => res(req.result||0); req.onerror = () => rej(req.error); }); db.close(); return v; } async function onData(dc) { dc.onmessage = async e => { const headLen = 128; // 简单头部:JSON 文本 const bytes = new Uint8Array(e.data); const head = new TextDecoder().decode(bytes.slice(0, headLen)).trim(); const meta = JSON.parse(head); const payload = bytes.slice(headLen); await saveChunk(meta.name, meta.index, payload); await saveProgress(meta.name, meta.index + 1); }; }

发表评论 取消回复