← All Workshops

MudEngine Part 11: Peer-to-Peer with iroh

Step 8 / 14

The WASM stub — browsers are step 2

Browsers cannot open UDP sockets, so a WASM tab can never speak QUIC directly. The desktop mesh is fully wired; the browser half would be a WebSocket relay the host runs, and this step ships the client-side stub for it as relay.rs:

  • relay::connect(&my_name, &my_id, relay_ws_url) — the exact same (Session, event_receiver) shape the desktop net::connect returns, so components/game.rs cannot tell the transports apart.
  • It currently always errors with a clear message — the relay is not compiled into this build.

The wire protocol on the other end is the same Packet type, and the WASM half of net::connect (the #[cfg(target_arch = "wasm32")] branch) already routes through it. When you build step 2 — a tiny tokio WebSocket listener that broadcasts client bytes into the gossip topic and pipes NetEvents back out — this stub's signature is the contract. Desktop P2P does not wait on it.

mud-engine/src/game/relay.rs
//! Browser → WebSocket relay client (Part 11, step 2).
//!
//! Browsers cannot open UDP sockets, so a WASM tab can never speak QUIC/iroh
//! directly. Instead the host runs a tiny relay that speaks WebSocket on one
//! side and subscribes to the gossip topic (QUIC) on the other. This module
//! is the WASM half of that bridge: it connects to `ws://<relay-address>:9090`
//! and speaks the exact same [`super::net::Packet`] wire protocol the desktop
//! peers use — from the UI's point of view the relay is invisible.
//!
//! `relay_ws_url` is a plain `ws://` address rather than an iroh node id,
//! because browsers have no node id to dial with.

use super::messages::ServerMessage;
use super::net::Session;
use tokio::sync::mpsc::UnboundedReceiver;

/// Connect over WebSocket. This build ships desktop-only (browsers cannot
/// open UDP sockets, so QUIC is impossible from a tab), so the WASM stub
/// always errors. Step 2 of Part 11 fills in the relay.
pub async fn connect(
    my_name: &str,
    my_id: &str,
    relay_ws_url: &str,
) -> Result<(Session, UnboundedReceiver<ServerMessage>), String> {
    let _ = (my_name, my_id);
    Err(format!(
        "relay support is not compiled into this build (relay url {relay_ws_url:?})"
    ))
}
🔍 Relay vs. fullstack server

The relay is not a game server. It does not own GameState, does not validate moves or quest logic, and does not persist anything. It is transport only: WebSocket bytes in → gossip bytes out. That is the key insight of the hybrid architecture — browsers become peers with ~30 lines of plumbing instead of a second authoritative node.

Step 8 / 14