oakkar

Game night taught me WebRTC.

My friends and I had a deck of cards and no poker chips. Turning our phones into controllers ended up being the most fun way I could have learned WebRTC.

Checked against the code on 6 min read

  • WebRTC
  • Data channels
  • Cloudflare

Why I bothered learning WebRTC

It started on a game night when my friends and I had a deck of cards, plenty of time, and zero poker chips. I threw together a quick chip tracker, and over a few weeks it snowballed into PlayKit: poker chips, a chess clock, scorekeeping, tournaments, Undercover, and Imposter.

Passing one phone around the table gets old fast, so I wanted everyone to join on their own phone. That gave me an excuse to finally learn WebRTC. Most tutorials jump straight into video calls, which I didn’t need at all. I just wanted a clean way to send small game moves and table updates over a data channel between one host laptop (or phone) and everyone else at the table.

Before building this, I half-assumed “peer-to-peer” meant two browsers could just magically talk without a server. Turns out the first thing WebRTC teaches you is how much work goes into getting two devices to meet in the first place.

Getting two browsers to meet

When someone hosts a room in PlayKit, they get a join link to share with the table. Each friend who opens it connects to a tiny signaling service I put on Cloudflare, and the host opens a separate WebRTC connection to each guest.

How a phone joins a game

Signaling introduces the browsers, then game data goes directThe host and guest exchange SDP offers, answers, and ICE candidates through a Cloudflare Worker and room Durable Object over WebSockets. Both use STUN to discover public address candidates. ICE checks possible paths. An encrypted WebRTC data channel carries game actions and snapshots directly between host and guest. A dashed TURN relay is an optional extension, currently disabled. Numbered markers match the five connection steps listed after the diagram.Cloudflare signalingWorker + room Durable ObjectWebSocketWebSocketOffer / answer / ICE candidatesHost browserRuns the gameGuest phoneSends player movesEncrypted data channelMoves / table snapshotsSTUN discoveryTURN relay · not enabled
Hit play to watch the five steps below light up in order. Blue envelopes pass through Cloudflare just to get the two browsers talking; once the green line opens, chips and table updates go straight between host and phone.
Connection setupGame dataOptional relay
  1. Meet through signaling. Both the host and the joining phone open authenticated WebSockets to a Cloudflare Worker backed by a room Durable Object. This server has one job: pass setup notes back and forth.
  2. Swap an offer and an answer. The host creates an ordered data channel called playkit-v1 and sends an SDP offer describing how it wants to talk. The phone saves that as its remote description and sends back an SDP answer.
  3. Trade possible network routes. Each browser collects ICE candidates (possible addresses it might be reachable on) and trickles them through signaling. One detail that tripped me up early: candidates can show up before the remote description is ready, so PlayKit queues them and applies them once it is.
  4. Test routes and open the channel. ICE tries candidate pairs until it finds a path that actually responds. Once the encrypted data channel opens, the phone can ask for a seat—though the host still has to approve it.
  5. Hand control to the host. From here on, the host checks every move and sends updated game snapshots back out. Just reaching the signaling server doesn’t put you in the game.

If you want the official walkthrough of this handshake, WebRTC’s peer-connection guide is the clearest reference I found.

What goes over which wire

Signaling (Cloudflare)

WebSocket to the Worker and room Durable Object

  • SDP offer and answer
  • ICE address candidates
  • Invite check during join
  • Basic room and peer metadata

Only for introductions

Data channel (direct)

Encrypted, ordered playkit-v1 channel between host and guest

  • Seat requests
  • Bets, folds, and other moves
  • Full table snapshots, cards included

Everything about the actual game

The Cloudflare side never sees a card or a bet. Even the invite link stays out of the initial HTTP request by living after the # in the URL, and the Durable Object only keeps a SHA-256 hash of it.

ICE, STUN, and TURN (the part that confused me most)

Every time I read about WebRTC before this project, these three acronyms blurred together. Seeing them next to actual routers finally made them click. A phone sitting on Wi-Fi or mobile data usually has a private local IP that nobody outside its router can reach, and firewalls love dropping unexpected traffic.

Getting past two routers

Example addresses
STUN reveals public addresses; ICE checks which route answersThe host browser and guest phone each sit behind a router. Each browser knows its local address and asks a STUN server what address it sees, learning the public address its router presents. ICE checks candidate pairs between the two browsers. In this example one route is blocked by a router and another answers, becoming the direct route. A TURN relay that could carry traffic between the routers is shown dashed because PlayKit does not deploy one.STUN serverReplies with your public IPWhat IP doyou see?What IP doyou see?A pair that answers becomes the routeBlocked by a routerRouter / NATRouter / NATseen as 203.0.113.7seen as 198.51.100.4Host browserlocal 192.168.1.20Guest phonelocal 10.0.0.8TURN relayNot deployed yet
Each device asks STUN what address it looks like from the outside, then ICE tests pairs until something answers. If both routers are too strict, you’d need a TURN relay to bridge them—and right now PlayKit doesn’t run one.
STUN discoveryWorking routeBlocked checkRelay, not deployed
ICE
Interactive Connectivity EstablishmentThe matchmaker. It gathers every possible address a device could use (local, STUN, or TURN), tests pairs between the two browsers, and picks one that actually works. ICE isn’t a server carrying your data—it’s the process that finds the route.
STUN
Session Traversal Utilities for NATA lightweight “what’s my public IP?” helper. Your browser pings a STUN server, and the server replies with the public IP and port your router showed it. That’s often enough for two devices to punch through and talk directly, though STUN never carries the actual game traffic.
TURN
Traversal Using Relays around NATThe fallback plan. When strict routers or corporate firewalls refuse a direct connection, a TURN server sits in the middle and relays the encrypted traffic for both sides. It makes connections way more reliable, at the cost of paying for and running relay bandwidth.

MDN’s page on WebRTC protocols goes deeper if you want the full spec breakdown.

Tradeoffs I made along the way

One host runs the table

When I first sketched this out, I wondered if every phone should connect to every other phone in a mesh. Five minutes of thinking about poker cured me of that. If two people tap a button at the same instant, who resolves the conflict? And with five friends at a table, a mesh means ten connections to babysit instead of four.

Why one host instead of a mesh

5 players around a table
Full mesh versus host-centered starOn the left, five phones in a full mesh need ten peer connections, and every phone has to agree on the same game state. On the right, PlayKit's star topology connects each guest phone only to the host browser: four connections, with one browser validating every move.Full mesh10 connections · everyone syncs with everyoneP1P2P3P4P5PlayKit (star)4 connections · one host owns the tableP1P2P3P4Host
With five people at a table, a mesh means ten connections and five copies of the rules trying to stay in sync. A star keeps it to four connections and one referee.

Instead, PlayKit uses a simple star: every guest talks only to the host. Guests send requests (“I want to raise”), the host checks whether it’s valid, and the host broadcasts the new state. If the host closes their laptop, the room ends—there’s no automatic host migration. For a living-room game night, I’m totally fine with that tradeoff.

Gain
One place to check rules and settle conflicts, with far fewer connections to manage.
Cost
No host migration. If the host browser drops out for good, the session goes with it.

For poker specifically, the host checks three things on every incoming move: does this player own that seat, are we still on the revision they think we’re on, and is the move actually legal? If everything passes, the host saves the move locally first, then sends each phone only the slice of state it’s allowed to see. Undo history and duplicate-action tracking never leave the host.

What happens when a player taps Raise

  1. Guest phone

    Sends a bet for its seat, tagged with the table revision it last saw.

    Raise · on r41

  2. Host browser

    • Is it this player’s seat?
    • Are we still on r41?
    • Is the bet legal?

    Saves the move locally first

  3. Everyone’s phone

    Gets a fresh snapshot trimmed to only what that player should see.

    Snapshot r42

Phones only ask; the host decides. Undo history and duplicate-action checks stay on the host too.

Full snapshots instead of a replay log

Because a poker hand or a score sheet is tiny, I didn’t bother building a delta/replay protocol. PlayKit uses an ordered data channel and sends a full snapshot on every state revision. If a friend’s phone locks and misses two turns, I don’t have to figure out which deltas to replay—they just get the latest snapshot when they wake up.

I also made the buttons stay locked whenever a phone drops or reconnects. You can’t tap a blind bet while offline and hope it goes through later; your controls only turn back on after a fresh snapshot lands from the host. Once the data channel opens, the phone also repeats its hello once a second (up to a 30-second timeout) until the host answers, so a lost opening message doesn’t leave someone stuck on a spinner.

When a phone goes to sleep mid-hand

Time runs left to right
Missed revisions are skipped, not replayedThe host publishes snapshots r40, r41, r42, and r43. The phone receives r40, then goes offline and misses r41 and r42. After it reconnects, the host sends a validated snapshot at the current revision, r42, which contains the full game. The phone's controls stay off from the moment it disconnects until that snapshot arrives. It then receives r43 as usual.HostPhoneScreen locked / offliner40r41r42r43Skipped, not replayedWakes upr42Latest snapshotWhole tableButtons activeButtons locked until r42 landsButtons active
Because every snapshot holds the whole table, a phone that missed r41 and r42 doesn’t need a replay log—it just grabs r42 and its buttons turn back on.
Gain
No stale-screen mistakes or messy offline merge logic.
Cost
You wait a beat after reconnecting for the latest snapshot before your buttons come back.

Keeping the game off my signaling server

I wanted the Cloudflare side to know as little as possible about what’s happening at the table. Cards, bets, and snapshots only travel over the encrypted peer-to-peer channel, never through the Worker or Durable Object.

For invite links, I tucked the secret into the URL fragment (the part after #). Browsers don’t send the fragment to the web host on the initial page load, and the join page strips it out of the address bar as soon as it saves the credentials. The phone does still send that invite during the WebSocket signaling handshake so the room can verify it, and the Durable Object only stores a SHA-256 hash of it.

Gain
Game state never touches the signaling server, and raw invites aren't stored there.
Cost
The signaling server still checks the invite during auth and can see basic connection metadata.

What I still want to test

Most of my testing so far has been on my own laptop and Wi-Fi. There are a few real-world things I haven’t actually measured yet:

  • Try physical phones across different Wi-Fi and mobile data combos to see where STUN-only breaks.
  • Log which ICE candidate pairs actually win in practice (local vs. server-reflexive).
  • Watch what happens when a phone sleeps for ten minutes mid-game and wakes back up.
  • Price out a small TURN relay and decide if it’s worth running for a side project.

Read the code

Everything here matches PlayKit as I checked it on 20 October 2026 (commit 5822c97). If you want to poke around, docs/phone-sync.md lays out the authority and recovery rules, and src/sync/transport.ts has the actual WebRTC offer/answer flow, candidate queue, and data channel setup.

Back to PlayKitMore learning notes