JFLib

game/src/net/server.rs#

Source: lib/game/src/net/server.rs

server -- the server-authoritative side of the netcode, without I/O: netchan's events in, messages out

  RoomSim        what a game puts into a room: its schema, the map's baseline, join and leave, one tick
                 with the players' inputs, the replicated world, the priority of an entity for a viewer,
                 and the reliable events both ways (on_event, take_events)
  NetServer      rooms by code, connections by netchan id; on_event takes netchan's ServerEvents (of a
                 netchan::Server with sockets or of an endpoint::ServerCore on a simulated network),
                 advance(now) runs the ticks due at the fixed rate, take_out / take_close say what to send
                 and which connections to end

A tick: every room hands each player the input of this tick (InputBuffer: the client's own, or the last
one repeated when it did not arrive in time) to its RoomSim; every snapshot_every ticks each client gets
a snapshot.  A snapshot is a delta against a base the client holds: over a WebSocket the last one sent
(reliable and ordered), over UDP the newest the client confirmed it decoded (INPUT's ack) or, when that
is better, the newest complete one it confirmed (the FULL it fetched), else the map's baseline.  Its
changes are ordered -- the client's own figure, what is gone, then by a priority added up per snapshot
until the entity is sent -- and cut to the budget (1200 bytes unless set: netchan does not fragment).
What was sent is remembered per client exactly as the client will hold it.  The events of the room
(RoomSim::take_events) ride in every snapshot until the client acknowledges them (event.rs); the client's
events come with its INPUTs and reach the RoomSim at the start of the next tick.

Rooms are independent: a room's tick (its inputs, its step, its events, its snapshots) touches nothing of
another room.  With set_parallel the rooms of a tick run side by side on plat's worker pool (one room per
item: one room per core with enough cores); their messages are merged in the order of the room codes, so
the server sends bit for bit what it sends on one thread.

Joining: HELLO -> WELCOME.  The full state goes with the first snapshot when it fits (a WebSocket always:
up to stream_budget).  A UDP client whose full state does not fit a datagram gets it filled in: its
snapshots are cut by priority, so it sees its own figure and the most important things at once and the
rest in the next snapshots (about 200 ms for 300 props, as fast as the fetch; the user's decision of
19.11.2026).  With ServerOptions::fetch_full it gets a ticket instead and fetches the full state over a
WebSocket of its own (FETCH -> FULL at the next snapshot tick; the user's first decision of 18.11.2026),
filled in by priority until the FULL arrives.  Leaving: LEAVE (or netchan's DISCONNECT) removes the
figure at once; a client that goes silent is removed when netchan's timeout ends its connection.

Room codes and tickets come from the server's generator: a seeded one (new: tests, the simulated network,
a practice mode in the browser) or the system's cryptographic random numbers (secure, with_random): a
ticket is sent to its client, and a seeded xorshift gives its state away with one output.
  • enum To who gets an event of a room
    • All -- every player of the room
    • Player(u16) -- the player with this figure
    • AllBut(u16) -- every player but this one

impl To

  • fn includes(&self, id: u16) -> bool whether the player with figure id gets it

  • struct RoomEvent an event a room sends to its players (RoomSim::take_events): reliable, in order, each delivered once

    • to: To -- who gets it
    • channel: u8 -- the game's channel (0 ..= 15)
    • data: Vec<u8> -- the game's bytes (at most event::MAX_EVENT)
  • trait RoomSim what a game puts into a room (see the module header)

    • fn schema(&self) -> &Schema the kinds of the replicated entities and their field counts
    • fn baseline(&self) -> &Snapshot the replicated entities as the map places them (every client builds the same from the map)
    • fn join(&mut self, name: &str) -> Option<u16> a player joins with this (cleaned, unique) name -> the net id of its figure (None: no place)
    • fn leave(&mut self, player: u16) the player's figure goes (it left, or its connection ended)
    • fn step(&mut self, tick: u32, dt: f64, inputs: &[(u16, NetInput, bool)]) one tick: every player's input (net id, input, false when it is the last one repeated)
    • fn snapshot(&self, tick: u32, out: &mut Snapshot) the replicated world after the tick (tick set, entities sorted by id)
    • fn priority(&self, viewer: u16, e: &Ent) -> u32 how much e matters to the player viewer now (added up every snapshot until it is sent)
    • fn on_event(&mut self, player: u16, e: &NetEvent) an event of the player with figure player (reliable, in order): at the start of the tick after it came, before step, by the figures' ids and in the order they came
    • fn take_events(&mut self, out: &mut Vec<RoomEvent>) the events of the last step for the players (asked after every step; their tick is the step's)
  • struct ServerOptions a server's settings

    • rate: u32 -- ticks a second
    • snapshot_every: u32 -- a snapshot every this many ticks
    • max_players: usize -- players a room takes
    • max_rooms: usize -- rooms at once
    • budget: usize -- the bytes of a snapshot (UDP's limit; netchan's max_payload)
    • stream_budget: usize -- the bytes of a join's state over a WebSocket and of a FULL (below netchan's max_stream_payload)
    • event_budget: usize -- the bytes of the events a snapshot carries at most (out of budget; it always carries one)
    • margin: u8 -- the margin the clients' inputs should arrive with (ticks)
    • max_rewind_ms: u32 -- how far back hits are rewound at most (ms; 300 unless set: the 100 ms of the interpolation buffer and 200 ms beyond them, the user's decision of 2026-11-19)
    • ws_port: u16 -- the WebSocket's port (WELCOME tells UDP clients where to fetch a full state; 0: none)
    • fetch_full: bool -- a UDP client whose full state does not fit a datagram fetches it over a WebSocket of its own (ws_port, a ticket); false unless set: its snapshots fill it in by priority, as fast and without a second connection (the user's decision of 2026-11-19)
    • hello_ms: u32 -- a connection must send HELLO within this long (ms)
    • ticket_ms: u32 -- a ticket stays good this long (ms)
    • empty_room_ms: u32 -- a room without players closes after this long (ms)
    • start_tick: u32 -- the first tick (tests start near the wrap)
    • history: usize -- snapshots remembered per client
  • struct ServerStats what the server counted

    • ticks: u64 -- ticks run
    • snapshots: u64 -- snapshots sent (FULL included)
    • snapshot_bytes: u64 -- their payload bytes
    • max_snapshot: usize -- the largest payload
    • partial: u64 -- snapshots cut by the budget
    • fulls: u64 -- FULL sent over a fetch's WebSocket, and their bytes
    • full_bytes: u64 -- the bytes of the FULLs
    • joins: u64 -- players who joined, refusals
    • refused: u64 -- HELLOs refused
    • left: u64 -- players who left with LEAVE
    • events_out: u64 -- events of the rooms queued for players
    • events_in: u64 -- events of players handed to their rooms
    • event_overflow: u64 -- players dropped because they did not acknowledge their events (event::MAX_PENDING waiting)
    • sizes: Vec<u16> -- the payload size of every snapshot (the first 200 000, for percentiles)
  • struct LinkStats what the server counted for one client

    • snapshots: u64 -- snapshots sent
    • bytes: u64 -- their payload bytes
    • partial: u64 -- cut by the budget
    • from_map: u64 -- based on the map's baseline
    • inputs: InputStats -- the inputs
    • events: OutboxStats -- the events to the client
    • events_in: InboxStats -- the events of the client
  • type RoomFactory<S> = Box<dyn FnMut(&RoomCode) -> S + Send> the factory of a room's simulation

  • struct NetServer<S: RoomSim> the server (see the module header)

impl<S: RoomSim> NetServer<S>

  • fn new(opts: ServerOptions, seed: u64, factory: RoomFactory<S>) -> NetServer<S> a server with these settings whose room codes and tickets come from a generator seeded with seed (the same codes every run: tests, the simulated network, a practice mode); factory makes a room's simulation. A server on the network takes secure() or with_random()
  • fn with_random(opts: ServerOptions, random: fn() -> u64, factory: RoomFactory<S>) -> NetServer<S> a server whose room codes and tickets come from random (a cryptographic source, such as plat::random_u64; secure() takes that one)
  • fn secure(opts: ServerOptions, factory: RoomFactory<S>) -> NetServer<S> a server whose room codes and tickets come from the system's cryptographic random numbers (plat::random_u64: Windows, Linux, Apple, Android)
  • fn options(&self) -> &ServerOptions the settings
  • fn tick(&self) -> u32 the next tick to run
  • fn stats(&self) -> &ServerStats what it counted
  • fn parallel(&self) -> bool whether the rooms run side by side (set_parallel)
  • fn rooms(&self) -> Vec<RoomCode> the codes of the rooms
  • fn room(&self, code: &RoomCode) -> Option<&S> a room's simulation
  • fn room_mut(&mut self, code: &RoomCode) -> Option<&mut S> a room's simulation for changing it
  • fn players(&self, code: &RoomCode) -> Vec<(u32, u16, String)> a room's players: (connection, figure id, name), in the order they joined
  • fn player_of(&self, conn: u32) -> Option<(RoomCode, u16)> the room and figure of a connection
  • fn send_event(&mut self, conn: u32, channel: u8, data: &[u8]) -> bool queue an event for the player on connection conn (besides those of its room) -> false when refused (no player there, too long, a bad channel, its outbox full)
  • fn create_room(&mut self) -> Option<RoomCode> make an empty room (a lobby could hand its code out) -> its code; None when the server has its rooms
  • fn take_out(&mut self) -> Option<(u32, Vec<u8>)> the next message to send: (connection, payload)
  • fn take_close(&mut self) -> Option<u32> the next connection to end (after what was sent to it)
  • fn on_event(&mut self, e: &ServerEvent) one of netchan's server events
  • fn max_rewind_ticks(&self) -> u32 the lag compensation's limit in ticks (max_rewind_ms at the rate)
  • fn advance(&mut self, now_ns: u64) -> u32 the clock stands at now_ns (any monotonic clock): the ticks due run -> how many
  • fn step(&mut self) one tick now

impl<S: RoomSim + Send> NetServer<S>

  • fn set_parallel(&mut self, on: bool) run the rooms of a tick side by side on plat's worker pool (plat::parallel_for, one room per item; the pool has a thread per core unless --threads N), or one after another (false, the default). Every room is deterministic as on one thread and the results are merged in the order of the room codes: the messages are the same bit for bit. Without threads (the browser without shared memory) the pool runs the rooms in turn.

Source: docs/API.md in the JFLib repository.