Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Data Channels

Data Channel Protocols: Negotiated Channels and Patterns

Design a message protocol on top of RTCDataChannel: negotiated channels with fixed ids, typed envelopes, request and response with ids, heartbeats and multiple channels.

A data channel gives you raw messages with no structure. Real apps need more: which kind of message is this, which reply belongs to which request, is the other side still there? This lesson builds a small protocol layer on top of RTCDataChannel and introduces negotiated channels, an alternative way to open channels that removes one round of waiting.

Everything here works on the loopback connections you used in earlier lessons, so you can run each example.

In-band and negotiated channels

By default a channel is in-band (also called announced): one side creates it, the SCTP layer sends an "open" message, and the other side learns about it through ondatachannel.

A negotiated channel skips that announcement. Both peers call createDataChannel themselves with negotiated: true and the same id:

JavaScript
// on both peers, with the same id
const control = pc.createDataChannel('control', { negotiated: true, id: 0 });

There is no datachannel event for it. Instead the channel opens on both sides as soon as the transport is ready. Benefits:

  • You can set the options on both ends, so nothing depends on who created it.
  • You can use the channel as soon as the connection is up, even if one peer is not ready to react to events yet.
  • Ids are chosen by you, so channel 0 is always "control" on both sides.

Rules: id must be a number from 0 to 65534, both sides must use the same value, and you must not reuse an id for two channels. Passing negotiated: true without id throws a TypeError.

JS Negotiated channels

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The event count is zero: with negotiated channels, nobody gets announced to.

A message envelope

Once you send more than one kind of message, wrap each one in a small object with a type and a payload:

JavaScript
{ "type": "chat", "from": "ana", "text": "Hi" }
{ "type": "cursor", "x": 120, "y": 80 }
{ "type": "ping", "t": 1700000000000 }

The receiver reads type and dispatches to a handler. Add a version number ("v": 1) or set the channel's protocol option to something like "app-v1" so you can change formats safely later. Always validate what arrives: a peer is just another program, and it can send nonsense. Never put remote strings into innerHTML.

Request and response

Sometimes one peer asks and the other answers. Give every request an id, store a promise under it, and settle that promise when a response with the same id arrives.

sequenceDiagram
  participant A as Peer A
  participant B as Peer B
  A->>B: { id: 1, type: "request", method: "sum", args: [2, 3] }
  B-->>A: { id: 1, type: "response", result: 5 }
  Note over A: promise 1 resolves with 5

The id links a response to its request, even if other messages arrive in between.

JS Promise-based RPC over a channel

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both calls and errors travel as ordinary messages, and promises make the code read like local function calls. In a real app add a timeout to each pending promise so a lost reply does not hang forever.

Heartbeats

An open channel does not prove the peer is alive. If the other browser tab freezes, or a laptop sleeps, the channel may stay open for a long time. A heartbeat is a tiny ping every few seconds; if no pong arrives within a limit, you treat the peer as gone and start recovery (see WebRTC in Real Apps). The ping can also measure round-trip time, as you will do in Practice.

Several channels versus one

Open a separate channel when two kinds of traffic need different delivery rules (reliable chat versus unreliable positions) or you do not want one slow transfer to delay small messages. Keep to one channel when ordering between the messages matters, because ordering is only guaranteed within a channel, not across channels.

Common mistakes

  • Using negotiated: true on only one side. The other peer's channel never matches.
  • Reusing an id. Two channels with the same id on one connection is an error.
  • Trusting incoming JSON. Validate type and fields; wrap JSON.parse in try/catch.
  • Request ids that restart at 1 after a reconnect. Old replies could match new requests; create a fresh rpc object per channel.
  • Expecting order across channels. There is none.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is different about a negotiated data channel?

    Negotiated channels are created on both sides with a matching id, so no in-band announcement or datachannel event is used.
  2. 2. Why include an id in each request message?

    Responses can arrive in any order relative to other traffic; the id links each reply to its promise.
  3. 3. What does a heartbeat detect that readyState does not?

    A channel can stay open for a long time after the other side vanished; missing pongs reveal it.
  4. 4. When is order guaranteed?

    Each channel is its own SCTP stream; ordering applies within an ordered channel, not between channels.

Summary

  • Negotiated channels use a shared id on both peers and skip the datachannel event.
  • Wrap messages in envelopes with a type, validate them, and version your protocol.
  • Request ids plus promises give you RPC-style calls; add timeouts in real code.
  • Heartbeats find dead peers; extra channels separate traffic with different needs.

Next: STUN Servers and NAT