Real-Time Streaming Systems (WebRTC + Live Data) · Lezione

Trasferimento di file tramite i canali dati WebRTC

Impari a inviare file peer-to-peer attraverso i canali dati WebRTC, inclusi chunking, backpressure, ordinamento e monitoraggio dell’avanzamento.

Lezione 4 di 413 passaggi

Trasferimento di file tramite i canali dati WebRTC è una lezione Real-Time Streaming Systems (WebRTC + Live Data) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Real-Time Streaming Systems (WebRTC + Live Data), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Real-Time Streaming Systems (WebRTC + Live Data) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Beyond Chat: Sending Files

WebRTC data channels are not limited to text chat. They can carry arbitrary binary data, which makes peer-to-peer file transfer possible without uploading to a server.

This keeps large files off your infrastructure and lowers latency.

Binary Types on the Channel

A data channel can send strings or binary. For files you set binaryType so received data arrives as an ArrayBuffer.

const channel = pc.createDataChannel('file');
channel.binaryType = 'arraybuffer';

Why You Must Chunk

You cannot send a 500MB file in one message. Channels have a maximum message size (commonly around 256KB). Send the file as a sequence of chunks.

  • Slice the file into fixed-size pieces.
  • Send each piece in order.
  • Reassemble on the receiver.

Slicing a File

The browser File object supports slice(), which returns a Blob you can read as an ArrayBuffer.

const CHUNK = 16 * 1024;
let offset = 0;
function nextChunk(file) {
  const slice = file.slice(offset, offset + CHUNK);
  offset += CHUNK;
  return slice.arrayBuffer();
}

Sending the Metadata First

Before the bytes, send a small JSON header so the receiver knows the file name, type, and total size. This lets it show progress and build the final blob correctly.

channel.send(JSON.stringify({
  name: file.name,
  size: file.size,
  type: file.type
}));

The Backpressure Problem

If you push chunks faster than the network drains them, the send buffer grows and the page can crash. Watch bufferedAmount and pause when it is high.

channel.bufferedAmountLowThreshold = 65536;
if (channel.bufferedAmount > 1 * 1024 * 1024) {
  await new Promise(r =>
    channel.addEventListener('bufferedamountlow', r, { once: true }));
}

Ordered and Reliable Delivery

By default data channels are ordered and reliable (like TCP), which is exactly what file transfer needs.

For files, do not use the unordered/unreliable options that are good for game state. Keep the defaults.

Reassembling on the Receiver

The receiver collects each ArrayBuffer until the total received equals the announced size, then builds a Blob.

const parts = [];
let received = 0;
channel.onmessage = (e) => {
  parts.push(e.data);
  received += e.data.byteLength;
  if (received === meta.size) {
    const blob = new Blob(parts, { type: meta.type });
    save(blob, meta.name);
  }
};

Showing Progress

Compute a percentage from bytes sent or received versus total size. Update the UI on both ends so users see a live progress bar.

const percent = Math.round((received / meta.size) * 100);

Triggering the Download

Turn the finished Blob into a downloadable link using an object URL.

function save(blob, name) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = name; a.click();
  URL.revokeObjectURL(url);
}

Reliability and Resume

If a connection drops mid-transfer, you can resume by tracking the last acknowledged offset and restarting from there. Combine this with checksums to verify integrity at the end.

Quick Check

Test your understanding of data channel file transfer.

Recap

P2P file transfer over data channels: send metadata, slice into chunks, respect backpressure, keep ordered/reliable delivery, reassemble into a Blob, and download.

Gratis per iniziare

Impara Real-Time Streaming Systems (WebRTC + Live Data) con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Trasferimento di file tramite i canali dati WebRTC» è gratuita?

Sì — il testo completo di «Trasferimento di file tramite i canali dati WebRTC» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Real-Time Streaming Systems (WebRTC + Live Data), passa a CoddyKit PRO. Il corso Real-Time Streaming Systems (WebRTC + Live Data) include 4 lezioni in totale.

Cosa imparerò in «Trasferimento di file tramite i canali dati WebRTC»?

Impari a inviare file peer-to-peer attraverso i canali dati WebRTC, inclusi chunking, backpressure, ordinamento e monitoraggio dell’avanzamento. Eserciti Real-Time Streaming Systems (WebRTC + Live Data) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Real-Time Streaming Systems (WebRTC + Live Data)?

Non è richiesta alcuna esperienza precedente. Real-Time Streaming Systems (WebRTC + Live Data) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Trasferimento di file tramite i canali dati WebRTC»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Real-Time Streaming Systems (WebRTC + Live Data)?

Sì. Ogni lezione Real-Time Streaming Systems (WebRTC + Live Data) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Sincronizzazione dei metadati WebRTC
  2. Chat in tempo reale tramite canali dati
  3. Condivisione dello stato dell'applicazione in tempo reale
  4. Trasferimento di file tramite i canali dati WebRTC
← Torna a Real-Time Streaming Systems (WebRTC + Live Data)