Skip to content
dream-net
api

Server

Server, ServerConfig and ServerEvent.

Module dream_net::server, all re-exported from the root. Servers and clients shows them in use.

ServerConfig#

struct ServerConfig { pub public_address: SocketAddr, pub protocol_id: u64, pub max_clients: usize, pub transport: TransportConfig }
FieldMeaning
public_addressThe address clients connect to, which tokens name. Port 0 binds a free port and advertises it
protocol_idnetcode’s protocol id: the game’s protocol family. Tokens minted for another are refused
max_clientsClient slots, 1 to 256
transportThe TransportConfig

Clone, Debug, PartialEq.

ServerEvent#

enum ServerEvent<P> { Connected { peer, client_id }, Disconnected { peer, reason }, Rejected { peer, client_id, failure }, Message { peer, event, channel, payload: P } }

A lifecycle record or an event. P is the payload: &[u8] from poll, its length as usize from poll_into. Clone, Copy, Debug, Eq.

VariantFieldsMeaning
Connectedpeer: PeerId, client_id: u64A client completed the handshake and can be sent events. client_id is the authenticated id from its token
Disconnectedpeer: PeerId, reason: DisconnectReasonA connected client left, and its handle is now invalid. Every Connected is followed by exactly one
Rejectedpeer: PeerId, client_id: u64, failure: FailureA client authenticated with netcode but failed the handshake. It was never announced, and has been disconnected. peer is the handle it would have had
Messagepeer: PeerId, event: EventTypeId, channel: ChannelId, payload: PAn event from a connected client. peer is the authenticated sender

A peer’s Connected precedes its messages, and its Disconnected follows them.

Server#

struct Server

A server over netcode: its socket, its private key, and a connection per client slot. Debug prints the address, slot count, connected count, fingerprint and time, never the key. Dropping it stops netcode, which tells every client at once.

Creating#

fn new(config: ServerConfig, private_key: &Key, schema: Schema, time: f64) -> Result<Server, Error>

Checks the schema against config.transport with validate_for, binds the socket and starts accepting clients. time is the host’s clock now.

Errors: Error::Config for a transport configuration or schema that validate_for refuses; Error::Netcode for a max_clients outside 1 to 256 or a socket that cannot bind.

The server accepts connect tokens under these rules, all netcode’s:

  • Single use. A token that established a session admits nothing again on this server, from any address, even after that session ended.
  • Expiry. A token whose expire timestamp is not later than the server’s wall clock is refused.
  • The start floor. At start the server records the wall-clock second plus its maximum token lifetime, DEFAULT_MAX_CONNECT_TOKEN_LIFETIME (30 seconds) with new, and refuses every token that expires no later than that. A 30-second token is accepted from the wall-clock second after the start, and a token minted before a restart never is.

The floor only covers tokens no longer-lived than the maximum, so a host that keeps its private key across server starts must mint tokens with expire_seconds no longer than it; a host that generates a fresh key for each start is not exposed to replay across restarts. A refused token is never answered: its client reports ConnectFailed with TimedOut when its attempt runs out. Token timestamps and the floor use the wall clock; everything else uses the host’s time.

fn with_max_token_lifetime(config: ServerConfig, private_key: &Key, schema: Schema, time: f64, max_connect_token_lifetime_seconds: u32) -> Result<Server, Error>

As new, with max_connect_token_lifetime_seconds as the longest lifetime of the tokens this server’s backend issues, for the start floor above. Also Error::Netcode with NetcodeError::InvalidConnectTokenLifetime for a maximum of 0 or above i32::MAX.

const DEFAULT_MAX_CONNECT_TOKEN_LIFETIME: u32 = 30

The maximum token lifetime new uses, in seconds.

fn set_capture(&mut self, sink: Option<Box<dyn CaptureSink>>)

Installs a capture sink that records every event this server sends and every record it polls, or removes it with None.

The frame#

fn update(&mut self, time: f64)

Receives and processes everything that arrived, then advances timers. Call once per frame. A time earlier than the last is treated as the last. It accepts new clients, reports those that left, receives and delivers every datagram, completes handshakes, and fails connections that time out or send malformed data. A client that failed on a schema or protocol mismatch is kept, and its traffic ignored, for mismatch_linger seconds, then disconnected.

fn poll(&mut self) -> Option<ServerEvent<&[u8]>>

The next record, with its payload borrowed from the inbox until the next call, or None when the inbox is empty.

fn poll_into(&mut self, buffer: &mut [u8]) -> Result<Option<ServerEvent<usize>>, BufferTooSmall>

The next record, with an event’s payload copied into the front of buffer and its length in payload. If the payload does not fit, returns BufferTooSmall with the length it needs and consumes nothing.

fn send(&mut self, peer: PeerId, event: EventTypeId, payload: &[u8]) -> Result<(), SendError>

Queues an event to one client, copying the payload before it returns. Errors, with nothing queued: UnknownPeer for a handle that is not a connected client; UnknownEvent, PayloadTooLarge or QueueFull from its connection.

fn broadcast(&mut self, event: EventTypeId, payload: &[u8]) -> Result<usize, SendError>
fn broadcast_except(&mut self, except: Option<PeerId>, event: EventTypeId, payload: &[u8]) -> Result<usize, SendError>

Queues an event to every connected client, or every one but except. Returns how many clients’ queues refused it: on a reliable channel, those whose window was full. UnknownEvent and PayloadTooLarge are errors before anything is queued.

fn flush(&mut self)

Packs and sends everything queued, plus owed acknowledgements, hellos and idle packets. netcode only refuses a datagram outside 1 to 1200 bytes, which the transport configuration rules out; if it ever refused one, that client would be failed with TransportError rather than silently lose its traffic. Socket errors surface as loss, and in the end as a timeout.

Peers#

fn peers(&self) -> impl Iterator<Item = PeerId> + '_

Every connected client, in slot order.

fn num_connected(&self) -> usize
fn max_clients(&self) -> usize

Connected clients, and slots.

fn client_id(&self, peer: PeerId) -> Option<u64>
fn client_address(&self, peer: PeerId) -> Option<SocketAddr>
fn client_user_data(&self, peer: PeerId) -> Option<&UserData>

A connected client’s id and user data from its connect token, and its address.

fn stats(&self, peer: PeerId) -> Option<ConnectionStats>
fn counters(&self, peer: PeerId) -> Option<Counters>

A connected client’s link estimates and counters.

fn peer_connection(&self, peer: PeerId) -> Option<&Connection>

A connected client’s Connection, for diagnostics such as last_malformed and parked_bytes.

Each returns None for a handle that is not a connected client, including a stale one.

fn disconnect(&mut self, peer: PeerId)

Disconnects a client now. A connected client’s Disconnected { reason: Requested } is queued; a client still handshaking is dropped without a record. A stale handle does nothing.

fn disconnect_all(&mut self)

Disconnects every client, as disconnect does.

Everything else#

fn schema(&self) -> &Schema
fn address(&self) -> SocketAddr

The schema, and the address clients connect to, with the port it bound.

fn memory_usage(&self) -> MemoryUsage

Approximate native memory of every connection, with the inbox counted as receive.