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 Towho gets an event of a roomAll-- every player of the roomPlayer(u16)-- the player with this figureAllBut(u16)-- every player but this one
impl To
fn includes(&self, id: u16) -> boolwhether the player with figureidgets itstruct RoomEventan event a room sends to its players (RoomSim::take_events): reliable, in order, each delivered onceto: To-- who gets itchannel: u8-- the game's channel (0 ..= 15)data: Vec<u8>-- the game's bytes (at most event::MAX_EVENT)
trait RoomSimwhat a game puts into a room (see the module header)fn schema(&self) -> &Schemathe kinds of the replicated entities and their field countsfn baseline(&self) -> &Snapshotthe 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) -> u32how muchematters to the playerviewernow (added up every snapshot until it is sent)fn on_event(&mut self, player: u16, e: &NetEvent)an event of the player with figureplayer(reliable, in order): at the start of the tick after it came, before step, by the figures' ids and in the order they camefn 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 ServerOptionsa server's settingsrate: u32-- ticks a secondsnapshot_every: u32-- a snapshot every this many ticksmax_players: usize-- players a room takesmax_rooms: usize-- rooms at oncebudget: 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 ofbudget; 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 ServerStatswhat the server countedticks: u64-- ticks runsnapshots: u64-- snapshots sent (FULL included)snapshot_bytes: u64-- their payload bytesmax_snapshot: usize-- the largest payloadpartial: u64-- snapshots cut by the budgetfulls: u64-- FULL sent over a fetch's WebSocket, and their bytesfull_bytes: u64-- the bytes of the FULLsjoins: u64-- players who joined, refusalsrefused: u64-- HELLOs refusedleft: u64-- players who left with LEAVEevents_out: u64-- events of the rooms queued for playersevents_in: u64-- events of players handed to their roomsevent_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 LinkStatswhat the server counted for one clientsnapshots: u64-- snapshots sentbytes: u64-- their payload bytespartial: u64-- cut by the budgetfrom_map: u64-- based on the map's baselineinputs: InputStats-- the inputsevents: OutboxStats-- the events to the clientevents_in: InboxStats-- the events of the client
type RoomFactory<S> = Box<dyn FnMut(&RoomCode) -> S + Send>the factory of a room's simulationstruct 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 withseed(the same codes every run: tests, the simulated network, a practice mode);factorymakes 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 fromrandom(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) -> &ServerOptionsthe settingsfn tick(&self) -> u32the next tick to runfn stats(&self) -> &ServerStatswhat it countedfn parallel(&self) -> boolwhether the rooms run side by side (set_parallel)fn link_stats(&self, conn: u32) -> Option<LinkStats>a client's counts (None: no player on that connection)fn rooms(&self) -> Vec<RoomCode>the codes of the roomsfn room(&self, code: &RoomCode) -> Option<&S>a room's simulationfn room_mut(&mut self, code: &RoomCode) -> Option<&mut S>a room's simulation for changing itfn players(&self, code: &RoomCode) -> Vec<(u32, u16, String)>a room's players: (connection, figure id, name), in the order they joinedfn player_of(&self, conn: u32) -> Option<(RoomCode, u16)>the room and figure of a connectionfn send_event(&mut self, conn: u32, channel: u8, data: &[u8]) -> boolqueue an event for the player on connectionconn(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 roomsfn 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 eventsfn max_rewind_ticks(&self) -> u32the lag compensation's limit in ticks (max_rewind_ms at the rate)fn advance(&mut self, now_ns: u64) -> u32the clock stands at now_ns (any monotonic clock): the ticks due run -> how manyfn 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.