Skip to content
Journey to Code

Series

Rustbound / Server field manual 02

One World, Many Players

One owner.
Many connections.

The first Rustbound game lived in one process. Now Bryce, Ryan and Tommy all expect the same world to answer them at once—without copying it, corrupting it or making everyone wait.

  • Rust 2024
  • TCP
  • Ownership
  • Channels
  • Tokio
  • 4 lessons
WORLD CORE / OWNED STATETCP : 4000
Three connections. One authoritative world.
server.rs / Share the owner
for stream in listener.incoming() {
    let stream = stream?;
    let world = Arc::clone(&world);
    thread::spawn(move || {
        handle_player(stream, world);
    });
}

Bench test / Nothing leaves this page

Make Ryan wait on purpose

Connect Bryce and Ryan with one blocking connection loop. Then switch the architecture and give each connection its own worker. The model is deterministic: it opens no socket and starts no thread.

With one blocking connection loop, Bryce's handler keeps the server from returning to accept(). Ryan's connection can wait in the operating system's listen queue, but the application does not read Ryan's command until Bryce leaves. When the accept loop delegates each connection to a worker, it can return to accept() immediately.

The connection log

Every lesson leaves the server working and gives the next problem somewhere concrete to appear.

  1. 01 / Make one connection work

    A Server With Nobody to Talk ToBuild a Rust TCP server and client, send one welcome message across localhost and let Result and the question-mark operator carry I/O errors. · 2 min read
  2. One Message Is Not a ConversationKeep a Rust TCP client and server talking until quit, using loop, break, continue and the zero-byte read that means the connection closed. · 2 min read
  3. A String Is Not a CommandTurn TCP input into a Rust Command enum, use Option and let else for missing words, and return useful parsing errors instead of scattering string comparisons. · 2 min read
  4. 02 / Put players in one world

    The Second Player Is Still WaitingLet a Rust TCP server accept another player immediately by spawning a worker thread and moving each TcpStream into its connection handler. · 2 min read