room.direct
A direct line between two people in a room — their browser to yours, a few milliseconds apart. For games where every frame counts: a fighting game, a racer, air hockey.
A ctx.live room already pushes changes to everyone the moment they happen. But every message goes to Fave1’s server and back — tens of milliseconds nearby, a few hundred across an ocean. That is plenty for a shared list, a cursor or a board game, and too slow for a punch that has to land in the next frame. A direct line skips the server: one browser sends straight to the other.
room.set() — the score, whose turn it is, the board, who wonkept · everyoneroom.cursor() — a pointer, a selection, “typing…”everyone · 25 a secondroom.direct(sid) — inputs, positions, hitsfast · two peopleMost apps never need it. If you can’t say why 50 ms matters for yours, a room is simpler — and a direct line always sits inside one: you meet in the room, keep score in the room, and only the fast part goes on the line.
Calls
room.on('direct', (line) => …); // take lines others open to you — register first const line = await room.direct(sid, { lossy: true }); // open one to a person in the room, by their sid line.send({ f: 1204, keys: 5 }); // JSON up to 1 KB · false if the line isn't open or it's too big line.on('message', (data) => …); // also 'open' · 'close' · 'error' line.close(); line.open; // connected right now line.via; // 'direct' · 'relay' · 'room' — which way it's going line.rtt; // round trip in ms, measured every 2 s · null through the room line.lossy; // drops late messages instead of waiting line.sid; line.id; // their socket · their app-scoped id
No permission of its own — a line lives inside a room, and rooms use pub. Nothing on a line is stored anywhere, nobody else in the room sees it, and someone who joins later sees nothing of it.
Your first line in 30 lines
Two players, each moving a paddle; each sees the other’s. Everyone listens for lines, and whoever joins calls the people already there — so every pair ends up with exactly one line, however they arrive.
// A room per match. Put the code in the link you share — that's the invite. const code = new URL(location.href).searchParams.get('match') ?? 'LOBBY'; const room = await ctx.live.join(`pong:${code}`); const lines = new Map<string, DirectLine>(); function keep(l: DirectLine) { lines.set(l.sid, l); l.on('message', (d) => drawPaddle(l.sid, d as { y: number })); l.on('close', () => { lines.delete(l.sid); removePaddle(l.sid); }); } // 1. Take lines others open to you. Do this first — a line nobody listens for is declined. room.on('direct', keep); // 2. Call everyone already here. Newcomers will call you. for (const p of room.peers()) { room.direct(p.sid, { lossy: true }).then(keep, () => { /* they left, or don't take lines */ }); } // 3. Sixty times a second, send where your paddle is. Latest wins, so lossy is right. const timer = setInterval(() => { for (const l of lines.values()) l.send({ y: myPaddleY() }); }, 1000 / 60); // clearInterval(timer) in onDestroy
Run it in two tabs from fave1 dev and the paddles move together — see Testing it.
Opening a line
One side calls, the other takes it. direct(sid) opens a line to one person, by the sid you get from room.peers() or a peer event. On the other side the line arrives on room.on('direct'), already open. If both call each other at the same moment, each gets the same single line back — no duplicates, no event.
Listening is how your app says yes. A line shows each browser the other’s network address (below), so Fave1 opens one only when both apps want it: the other side has registered room.on('direct'), or has called direct() to you. Otherwise direct() waits 3 s — the other app may have just joined — and rejects with declined. Register the listener right after join(); an app that doesn’t use lines simply never registers one, and nobody can open a line to it. Someone who already has 8 lines in the room declines a ninth the same way.
In a room of strangers, ask first — through the room. Taking a line already connects the two browsers, so “take it, then ask Play?” has shown both addresses before anyone said yes. In a lobby, don’t register room.on('direct') at all. Send the challenge with room.cursor() — it reaches everyone in the room and is never kept — and when the other person says yes, both of you call direct(). Two calls to each other meet as one line, and no line ever opens to someone who didn’t agree.
// A lobby: no room.on('direct') here, so nobody can open a line to you until you say yes. const lobby = await ctx.live.join('lobby'); type Ask = { ask?: string; yes?: string }; // what goes in cursor() — a sid, never a name // Challenge: tell the room who you'd like to play. Only that person acts on it. function challenge(p: LivePeer) { lobby.cursor({ ask: p.sid }); } lobby.on('peer', (ev) => { if (ev.type !== 'cursor') return; const said = (ev.peer.data ?? {}) as Ask; // They challenged you — ask your player before anything connects. if (said.ask === lobby.me.sid) { ctx.ui.render([ ctx.ui.text(`${ev.peer.initial} wants to play.`), ctx.ui.button('Play', { onClick: () => { lobby.cursor({ yes: ev.peer.sid }); connect(ev.peer); } }), ctx.ui.button('Not now', { onClick: () => lobby.cursor({}) }), ]); } // They said yes to you — call them too. The two calls meet as one line. if (said.yes === lobby.me.sid) connect(ev.peer); }); async function connect(p: LivePeer) { try { startMatch(await lobby.direct(p.sid, { lossy: true })); lobby.cursor({}); // the challenge is answered — clear it } catch (err) { const e = err as Fave1Error; if (e.code === 'not-found') ctx.ui.toast(`${p.initial} just left.`); else if (e.code === 'declined') ctx.ui.toast('They’re in another match.'); else throw err; } } for (const p of lobby.peers()) showChallengeButton(p, () => challenge(p));
The answer has to come within 3 s of the first call — the one who said yes calls at once, so in practice it does. The same sid always gives the same line while it is open — calling direct() again just hands it back. One person can have up to 8 lines in a room at once, opened by them or to them.
How it connects
You never set any of this up. Fave1 opens the connection inside its own frame and tries, in order:
Your code is the same on all three. direct() resolves once the line is open whichever way it went, and send and message work identically. via can change while a line is open: if the connection between the two browsers fails mid-game while both are still in the room, the line moves to the room instead of closing — nothing sent in between is lost. (If your network drops, the room connection goes too; see When something goes wrong.) rtt is measured, never guessed — read both when you need them, they are always current.
// How many frames ahead to schedule your own input so theirs arrives in time. function inputDelay(l: DirectLine): number { const ms = l.via === 'room' ? 250 : (l.rtt ?? 80); // your guess until rtt arrives; through the room, assume slow const oneWay = ms / 2; return Math.min(8, Math.max(2, Math.ceil(oneWay / (1000 / 60)) + 1)); } // Tell the player — a quiet badge, not an error. function connectionLabel(l: DirectLine): string { if (l.via === 'room') return 'Slow connection'; return `${l.rtt ?? '…'} ms`; }
Lossy or reliable
Latest wins
A late message is dropped instead of holding up the ones behind it. For anything you send again next frame anyway: positions, aim, a ball’s state.
Every message, in order
Nothing is lost, nothing overtakes. A lost packet is resent, and what follows waits for it — a short stall on a bad network. For chat, moves in a turn, “I’m ready”.
The side that opens the line chooses; the other side reads line.lossy. A line has one mode — for the occasional message that must arrive on a lossy line, put it in the room (room.set) instead, or repeat it in the next few messages. Through the room every message arrives in order, whatever you chose.
Fighting games: send inputs, not positions
In a fighting game, positions aren’t enough: both screens must agree on exactly who hit whom on which frame. The way every online fighting game does it is lockstep — both browsers run the same game from the same inputs. Each frame needs both players’ input for that frame; you send yours a few frames early so it is there in time, you send the last few again in every message, and while you wait you send them again — so a dropped message, or a line moving to the room, never stalls the game.
const room = await ctx.live.join(`fight:${code}`); room.on('direct', (l) => start(l)); const other = room.peers()[0]; if (other) start(await room.direct(other.sid, { lossy: true })); function start(line: DirectLine) { const DELAY = 3; // frames ahead — see inputDelay() above const p1 = (room.me.sid ?? '') < line.sid; // both sides agree who is player 1 const mine = new Map<number, number>(); const theirs = new Map<number, number>(); const sent: { f: number; k: number }[] = []; let f = 0, waited = 0; // The first DELAY frames have no input on either side. for (let i = 0; i < DELAY; i++) { mine.set(i, 0); theirs.set(i, 0); } line.on('message', (d) => { for (const e of d as { f: number; k: number }[]) if (e.f >= f && !theirs.has(e.f)) theirs.set(e.f, e.k); }); function tick() { if (!line.open) return; if (theirs.has(f)) { // both inputs for frame f are here — step it const next = f + DELAY; const k = readKeys(); // a small number: one bit per button mine.set(next, k); sent.push({ f: next, k }); if (sent.length > 8) sent.shift(); line.send(sent); // the last 8 — any one message covers the gaps const a = mine.get(f) ?? 0, b = theirs.get(f) ?? 0; step(p1 ? a : b, p1 ? b : a); // same order on both screens mine.delete(f); theirs.delete(f); f++; waited = 0; } else if (++waited % 6 === 0) { line.send(sent); // still waiting? say your last 8 again — theirs may be waiting on yours } requestAnimationFrame(tick); } requestAnimationFrame(tick); }
Three rules make it hold: the game must be deterministic — same inputs, same result on every device, so no Math.random() (seed your own generator from the room) and no frame-time physics; inputs are small — 8 of them fit easily in 1 KB; and results go in the room — when the match ends, both sides write the winner with room.set, so a spectator or a latecomer sees it. Waiting for the other input costs a frame when the network hiccups; games that can’t afford that predict the other player’s input and rewind when the real one arrives (“rollback”) — the same loop, with a snapshot of your game state per frame.
When something goes wrong
via becomes 'room' and messages keep coming, slowershow a badgeclose with 'closed'back to the lobbyclose with 'left', and a peer leave“They left” · win by forfeitclose with 'lost' — your room connection went too; the room reconnects by itself and fires opencall again on openclose with 'gone'nothingAfter a 'lost' you come back into the room with a new sid; the others keep theirs and see you leave and join again (their line to you closes with 'left'). Find your opponent again by their id, which never changes, and call them — they take it as they did the first time:
const room = await ctx.live.join(`fight:${code}`); // Their id is stable across reconnects; their sid is not. let opponentId = ''; room.on('direct', (l) => { opponentId = l.id; play(l); }); room.on('open', () => { // the room came back after a drop const again = room.peers().find((p) => p.id === opponentId); if (again) room.direct(again.sid, { lossy: true }).then(play, () => showWaiting()); });
What the other side sees
A line connects two browsers, so each can see the other’s network (IP) address — as on any video call. Fave1 opens the connection inside its own frame: neither the page you’re on nor your app’s code sees the addresses or the relay credentials, and the room’s server never sees what you send on a direct line.
That is why a line needs both apps to want it. Where people already chose each other — an invite link, a private match code — listening with room.on('direct') is fine. Where strangers meet, ask through the room first and let both sides call (Opening a line), so no line opens to someone who didn’t say yes. People see the first letter of the other’s name and their avatar, never a name, the same as everywhere else in a room.
Limits and errors
Per message
As JSON. Over it, send() returns false and an error event says too-large.
Lines at once
Per person, per room — the ones you opened and the ones opened to you. A ninth is declined. Every pair needs its own line, so a full mesh tops out at 9 players.
Through the room
Only on a 'room' line, added up across all your lines going through the room — 60 Hz to one person fits twice. A direct line has no limit but the network’s.
Opening
8 s to go direct before falling back to the room; direct() gives up after 20 s with timeout.
room.on('direct') and no direct() back within 3 s — or they already have 8say sosid is in the room — they left, or the room reconnectedrefresh peers()sid, or your ownfix itjoin() finished, after leave(), or while it reconnectswait for opentoo-largefix itTesting it
- Two tabs, no setup. With
fave1 dev, open the same site in two tabs and open your app in both. They meet in a sandbox room in this browser, and lines open between them through it —viasays'room', and everything else behaves for real:declined,left,close. - A real connection. Switch Data to My account and open your build signed in on two browsers — the same account in two browsers is two people in a room. Lines go
'direct'now. Two devices on different networks — your phone on mobile data — show you real round trips. - The fallback. Open one side in Firefox with
media.peerconnection.enabledset tofalseinabout:config. That side has no WebRTC, so the line opens through the room — check your game still plays.
Questions
room.set; watchers draw from change.