← All Workshops

MudEngine Part 7: Save & Load

Step 12 / 17

Update the WebSocket Endpoint

The ServerMessage::State payload now includes room data so the client can render room names without hardcoded statics (this was already added to messages.rs in the previous step).

The mud_ws handler in src/game/server.rs needs a full rewrite: it now reads from GAME_STATE instead of PLAYERS, calls save_players() after every mutation, sends Vec<RoomInfo> in the initial state, and validates moves via persistence::can_move().

Replace the entire contents of src/game/server.rs:

🎯 Why rooms in the State message?

The client needs room names and descriptions to render the grid, sidebar, and description panel. Previously these came from static ROOM_NAMES and static ROOM_DESCS arrays compiled into the WASM bundle.

By sending them as part of the initial State message, we achieve two things:

  1. Single source of truth — the server defines the world; clients just display it
  2. Dynamic worlds — the TOML file can be edited without recompiling the client

The room data is included in the State message (sent once per connection), not in every broadcast. The client caches it in a Signal<HashMap<usize, RoomInfo>> for the component's lifetime.

mud-engine/src/game/server.rs
use dioxus::prelude::*;
use dioxus_fullstack::{WebSocketOptions, Websocket};

use super::messages::{ClientMessage, PlayerInfo, ServerMessage};
use super::persistence::{self, RoomInfo};

#[cfg(feature = "server")]
use super::persistence::GameState;

// ── Server-only state ──

#[cfg(feature = "server")]
mod srv {
    use std::sync::{LazyLock, Mutex};
    use tokio::sync::broadcast;

    use super::*;

    /// The authoritative game state — rooms and connected players.
    /// The world comes from Game.toml (static); players from Players.toml (live).
    pub static GAME_STATE: LazyLock<Mutex<GameState>> = LazyLock::new(|| {
        Mutex::new(GameState {
            rooms: persistence::load_world("Game.toml"),
            players: persistence::load_players("Players.toml"),
        })
    });

    /// Broadcast channel — every connected WebSocket subscribes.
    pub static BROADCAST: LazyLock<broadcast::Sender<ServerMessage>> = LazyLock::new(|| {
        let (tx, _) = broadcast::channel(64);
        tx
    });
}

// ── WebSocket endpoint ──

#[get("/api/mud_ws?name")]
pub async fn mud_ws(
    name: String,
    options: WebSocketOptions,
) -> Result<Websocket<ClientMessage, ServerMessage>> {
    let id = uuid::Uuid::new_v4().to_string();
    let player_name = name.clone();

    // 1. Register the new player and build room info for the client
    let room_infos: Vec<RoomInfo>;
    {
        let mut state = srv::GAME_STATE.lock().unwrap();
        state.players.insert(
            id.clone(),
            PlayerInfo {
                id: id.clone(),
                name: name.clone(),
                room: 4, // Town Square
            },
        );
        persistence::save_players(&state);

        // Rooms are already RoomInfo — the wire type — so they go straight out.
        room_infos = state.rooms.clone();
    }

    // 2. Subscribe to the broadcast channel
    let mut rx = srv::BROADCAST.subscribe();

    // 3. Announce the new player to everyone
    let _ = srv::BROADCAST.send(ServerMessage::PlayerJoined(PlayerInfo {
        id: id.clone(),
        name: name.clone(),
        room: 4,
    }));

    // 4. Build the initial state snapshot for this new player
    let initial_state = {
        let state = srv::GAME_STATE.lock().unwrap();
        ServerMessage::State {
            players: state.players.values().cloned().collect(),
            your_id: id.clone(),
            rooms: room_infos,
        }
    };

    // 5. Upgrade the HTTP connection to a WebSocket
    let ws = options.on_upgrade(move |mut socket| async move {
        let _ = socket.send(initial_state).await;

        // ── Message loop ──
        loop {
            tokio::select! {
                msg = socket.recv() => {
                    match msg {
                        Ok(ClientMessage::Move { direction }) => {
                            let dir = match direction.as_str() {
                                "n" => "north", "s" => "south",
                                "e" => "east", "w" => "west",
                                d => d,
                            };

                            let new_room = {
                                let mut state = srv::GAME_STATE.lock().unwrap();
                                let current = state.players.get(&id).unwrap().room;
                                let next = persistence::can_move(&state, current, dir);
                                if let Some(next) = next {
                                    state.players.get_mut(&id).unwrap().room = next;
                                    persistence::save_players(&state);
                                    Some(next)
                                } else {
                                    None
                                }
                            };

                            if let Some(room) = new_room {
                                let _ = srv::BROADCAST.send(
                                    ServerMessage::PlayerMoved(PlayerInfo {
                                        id: id.clone(),
                                        name: player_name.clone(),
                                        room,
                                    }),
                                );
                            }
                        }
                        Err(_) => break,
                    }
                }

                msg = rx.recv() => {
                    match msg {
                        Ok(server_msg) => {
                            if socket.send(server_msg).await.is_err() {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }
            }
        }

        // ── Cleanup on disconnect ──
        {
            let mut state = srv::GAME_STATE.lock().unwrap();
            state.players.remove(&id);
            persistence::save_players(&state);
        }
        let _ = srv::BROADCAST.send(ServerMessage::PlayerLeft { id });
    });

    Ok(ws)
}
💡 What changed from Part 6

The WebSocket handler now works with GAME_STATE instead of PLAYERS and EXITS:

OperationPart 6Part 7
Player joinPLAYERS.lock().unwrap().insert(...)GAME_STATE.lock().unwrap().players.insert(...) then persistence::save_players()
Movement validationIndex into EXITS[current] arraypersistence::can_move(&state, current, dir) — looks up room by ID
Movement updateWrite player.room = nextSame, then persistence::save_players()
Player leavePLAYERS.lock().unwrap().remove(&id)GAME_STATE.lock().unwrap().players.remove(&id) then persistence::save_players()
Room info for clientStatic ROOM_NAMES / ROOM_DESCSBuilt from state.rooms as Vec<RoomInfo>

Two things changed compared to Part 6: state now lives in GAME_STATE (loaded from the two TOML files), and every mutation is followed immediately by persistence. The last step replaces this with a background autosave that flushes once a minute.

Step 12 / 17