Real-Time & Streaming From Zero · Episode 04

Data Channels

Data Channels is Episode 04 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 04 · Real-Time & Streaming From Zero

The same peer connection that carried a webcam in the last episode can carry anything. Not video — arbitrary bytes. Chat messages, mouse positions, game state, a whole file — shoved directly from one browser to another with no server in the middle. That's RTCDataChannel, and it's the quiet half of WebRTC that powers multiplayer browser games, collaborative editors, and "drop a file in this tab and it appears in that one" tools.

By the end of this page you'll have a working peer-to-peer chat and a live round-trip latency meter running over a real data channel — no backend, no second machine. We do it with the loopback trick from Episode 02: two RTCPeerConnections in this one page, doing a genuine offer/answer handshake and talking to each other. A synthetic peer auto-chats and auto-pings so the demo is alive the instant it loads, before you type a single word. Then we'll send reliable vs unreliable, stream JSON state at a tick rate, and chunk an ArrayBuffer through the wire with a progress bar.

0 fps
datachannel: connecting…
Opening a data channel over the loopback. Watch for 'open'.

What you're looking at

Two peers, A and B, both living in this tab, connected by a real WebRTC data channel. A is you; B is a synthetic peer that types friendly nonsense and answers your pings. The canvas is a live log: blue bubbles are messages you sent, green bubbles are what came back over the wire, and the sparkline on the right is the measured round-trip time of the ping stream. The badge shows the channel's readyState — it starts connecting… and flips to open once the handshake completes, usually within a frame or two.

Step through the six stages with the stage selector. Everything is real: the bytes genuinely traverse an SCTP-over-DTLS data channel, the same transport a remote peer on the other side of the planet would use. The only thing we've faked is the distance.

Stage 1 — Open a data channel

A data channel is created from one side with createDataChannel(). The other side doesn't create anything — it receives the channel through the ondatachannel event once the handshake brings it to life. Both ends then get an onopen when the channel is ready to carry bytes, and an onmessage for everything that arrives.

This is the single most important rule of the episode, so we'll say it loud: you cannot send() until onopen has fired. Call it a millisecond early and you get an InvalidStateError. The channel goes connecting → open → closing → closed, and only open accepts data.

// One page, two peers — a real handshake with no server (loopback).
const A = new RTCPeerConnection();
const B = new RTCPeerConnection();
A.onicecandidate = e => e.candidate && B.addIceCandidate(e.candidate);
B.onicecandidate = e => e.candidate && A.addIceCandidate(e.candidate);

// A creates the channel; B is handed it via ondatachannel.
const chan = A.createDataChannel('chat');
chan.onopen    = () => badge('datachannel: open');   // only NOW may we send()
chan.onmessage = e  => log('me ◂ ' + e.data);

B.ondatachannel = (e) => {
  const peer = e.channel;                          // the SAME channel, B's end
  peer.onmessage = (ev) => peer.send('echo: ' + ev.data);
};

// The exact handshake order matters — see Episode 02.
const offer = await A.createOffer();  await A.setLocalDescription(offer);
await B.setRemoteDescription(offer);
const answer = await B.createAnswer(); await B.setLocalDescription(answer);
await A.setRemoteDescription(answer);

That's the whole connection. From here on it's just send() and onmessage — the API is almost identical to a WebSocket, except there's no server: the two browsers talk straight to each other.

Stage 2 — Send and receive text (a real chat)

With the channel open, a chat is two lines: chan.send(text) on one side, onmessage on the other. Type in the box under the demo and press Enter — your message goes out over A, arrives at B, and the synthetic peer fires back a reply over the same channel. To keep the room lively when you're not typing, B also volunteers a message every few seconds on its own. Nothing here is request/response; either side can speak whenever it likes, which is exactly what makes data channels feel like a phone line rather than a web request.

send() accepts a string, a Blob, an ArrayBuffer, or a typed-array view. For text you just hand it the string. For binary you set binaryType first (Stage 6). The channel preserves message boundaries — one send() becomes exactly one onmessage, unlike a raw TCP socket where you'd have to frame messages yourself.

Stage 3 — Round-trip ping (measure the latency)

Here's the trick that turns a chat into a network instrument. Send a message that carries a timestamp. The other side immediately echoes it back. When it returns, now − t is your round-trip time. No clock synchronization needed, because both timestamps are read from your clock — the remote peer never looks at the number, it just bounces it.

// (b) The ping: stamp it, echo it, subtract — that's RTT.
function ping() {
  chan.send(JSON.stringify({ type: 'ping', t: performance.now() }));
}

// On the FAR side, bounce pings straight back, untouched:
peer.onmessage = (e) => {
  const m = JSON.parse(e.data);
  if (m.type === 'ping') peer.send(JSON.stringify({ ...m, type: 'pong' }));
};

// Back HOME, the pong's timestamp is still ours — so RTT is trivial:
chan.onmessage = (e) => {
  const m = JSON.parse(e.data);
  if (m.type === 'pong') {
    const rtt = performance.now() - m.t;     // milliseconds, round trip
    drawSparkline(rtt);
  }
};

On a loopback the raw RTT is essentially zero — the bytes never leave the process — so the demo adds a slider-driven synthetic delay to make the sparkline interesting and to foreshadow Episode 06's latency simulation. On a real connection this exact code is how every multiplayer game shows you your "ping," and how it decides how far ahead to predict the other player's moves.

Stage 4 — Reliable vs unreliable

By default a data channel is reliable and ordered: every message arrives, exactly once, in the order you sent it — TCP-like. That's perfect for chat and files, where a dropped or reordered message is a bug. But it has a cost: if one packet is lost, everything behind it waits while it's retransmitted. That stall is called head-of-line blocking, and for real-time data it's the enemy.

For a 60-times-a-second stream of player positions, you don't want last frame's position redelivered late — you want this frame's, now, and you'd rather drop the stale one. So you create an unreliable, unordered channel — UDP-like — and configure it to never retransmit:

// (c) Unreliable + unordered: for data where "fresh" beats "complete".
const fast = pc.createDataChannel('state', {
  ordered: false,      // don't hold packets to preserve order
  maxRetransmits: 0,    // never resend a lost packet — drop it
});
// (or maxPacketLifeTime: 50 — "give up after 50ms" instead of a retry count)

// Use UNRELIABLE for: cursor/player positions, voice, anything you re-send constantly.
// Use RELIABLE (the default) for: chat, files, game events you can't afford to lose.

You set the mode at creation time — it can't change later, and both ends inherit it from the offer/answer. Flip the reliability selector and toggle the drop simulation in this stage: the reliable stream stays gap-free even as we "lose" packets (they're resent), while the unreliable stream shows the gaps — and stays perfectly current. That trade — complete but maybe late vs fresh but maybe missing — is the whole reason both modes exist.

Stage 5 — Structured state at a tick rate

Real apps don't send loose strings; they send state objects. Serialize a snapshot to JSON, send it on a fixed timer (the "tick"), and parse it on the far side. Here the synthetic peer broadcasts its position, velocity, and a little health bar a few times a second — drag the send rate slider and watch the tick rate change. This is a deliberate preview of Episode 06: a multiplayer game is, at heart, exactly this loop — serialize state, tick it across the channel, reconcile it on arrival.

// A fixed-rate "tick" that streams a JSON snapshot over the channel.
function tick() {
  if (chan.readyState !== 'open') return;       // always guard readyState
  const snapshot = { seq: seq++, x: me.x, y: me.y, vx: me.vx, hp: me.hp };
  chan.send(JSON.stringify(snapshot));
}
setInterval(tick, 1000 / rate);                     // e.g. 6–30 ticks per second

// On arrival, parse and store the latest snapshot per peer:
chan.onmessage = (e) => { const s = JSON.parse(e.data); world.set(s.seq, s); };

JSON is the easy, debuggable default and it's what we use here. For a real game you'd eventually pack state into a compact binary buffer (a few bytes per field instead of a verbose string) — but the shape of the loop never changes, and JSON is the right place to start.

Stage 6 — Send a "file" (chunk an ArrayBuffer)

You cannot shove a 5 MB file into one send(). Data channels have a message-size limit — reliably safe at around 16 KB per message across browsers — so anything large must be chunked: slice the buffer, send the pieces in sequence, and reassemble them on the far side. This stage generates a synthetic "file" (a fake image buffer), streams it through the channel in 16 KB chunks, and fills a progress bar as the bytes arrive.

The subtlety is backpressure. send() returns instantly even if the network hasn't actually shipped the previous chunk — the bytes pile up in an internal queue, and its size is bufferedAmount. Blast a whole file in a tight loop and you'll balloon that buffer (or get an error). The fix: watch bufferedAmount and pause when it's high, resuming on the bufferedamountlow event.

// (d) Chunk an ArrayBuffer: slice → send sequentially, watching bufferedAmount.
const CHUNK = 16 * 1024;            // 16 KB — a safe cross-browser message size
chan.binaryType = 'arraybuffer';       // so onmessage gives us ArrayBuffers
chan.bufferedAmountLowThreshold = 256 * 1024;

let offset = 0;
function pump() {
  while (offset < file.byteLength) {
    // backpressure: if the queue is full, stop and wait for the low event
    if (chan.bufferedAmount > 1 * 1024 * 1024) return;
    const slice = file.slice(offset, offset + CHUNK);
    chan.send(slice);
    offset += CHUNK;
  }
}
chan.onbufferedamountlow = pump;     // resume when the queue drains
pump();

// Receiver: collect chunks, reassemble when the byte count is complete.
const parts = [];
peer.onmessage = (e) => {
  parts.push(e.data);
  received += e.data.byteLength;
  progress(received / total);
  if (received >= total) {
    const blob = new Blob(parts);   // the file, rebuilt — done!
  }
};

That's a real, serverless file transfer — the bones of every "AirDrop in the browser" app. A production version adds a tiny header per chunk (an id and offset) so multiple files can interleave, and sends a final "done" message with the filename and total size so the receiver knows when to assemble.

Common pitfalls

  • Sending before onopen. A fresh channel is in connecting state; calling send() throws InvalidStateError. Always gate sends on onopen (or check chan.readyState === 'open'), and queue anything you produce before then.
  • Flooding the buffer (backpressure). send() never blocks, so a tight send loop just grows bufferedAmount until memory bloats or the send fails. Watch bufferedAmount and pause on a threshold, resuming via bufferedamountlow — as in Stage 6.
  • Forgetting binaryType. The default is 'blob', so binary onmessage hands you a Blob you then have to read asynchronously. Set chan.binaryType = 'arraybuffer' up front if you want synchronous byte access.
  • Oversized messages. There's a per-message ceiling (treat ~16 KB as the universally safe limit; larger can silently fail or close the channel on some stacks). Chunk anything big — don't assume one send() can carry a whole file.
  • Picking the wrong reliability. Reliable+ordered for chat, events, and files; unreliable+unordered for high-frequency state you re-send constantly. Reliable on a 60Hz position stream causes head-of-line stalls; unreliable on a chat drops messages. The mode is fixed at creation — choose deliberately.
  • Not pruning on close. Listen for onclose and onerror; a peer can vanish mid-transfer. Don't leave half-assembled files or dead channels in your state.

Exercises

  1. Typing indicator. When the input box fires an input event, send a small {type:'typing'} message (throttled to a few per second). On the far side, show a "peer is typing…" line that clears after ~1.5s of silence. You've just built the feature every chat app has — over a raw data channel.
  2. Send a small image as chunks. Swap the synthetic file buffer in Stage 6 for a real one: draw something to an offscreen <canvas>, get a Blob via canvas.toBlob(), read it as an ArrayBuffer, and stream it through the same chunker. Reassemble the parts into a Blob and paint it back with createImageBitmap().
  3. Jitter / drop simulator. Wrap the channel's receive path in a function that delays each message by a random amount and randomly drops a percentage (add a slider for drop rate). Watch how the ping sparkline gets spiky and the structured-state stream develops gaps — then re-derive why unreliable mode is the right call for real-time data. (This is a direct warm-up for Episode 06.)

What's next

Episode 05 — Multiplayer cursors across tabs. We take everything from this episode — open a channel, stream JSON state at a tick rate — and point it at a second browser tab using BroadcastChannel, so you can see other cursors moving live with zero server. Then bots fill the room so it's a party even when you're alone. The data channel you just learned is the muscle; presence is the choreography.