Skip to main content

Client

Struct Client 

Source
pub struct Client<E: Copy + Eq + Hash + Send + Sync> { /* private fields */ }
Expand description

The naia client — connects to a server, receives replicated entities, and sends client-authoritative mutations and messages.

E is your world’s entity key type (e.g. a u32 or ECS Entity). It must be Copy + Eq + Hash + Send + Sync.

§Minimal client loop

loop {
    client.receive_all_packets();                      // 1. read UDP/WebRTC
    client.process_all_packets(&mut world, &now);      // 2. decode + dispatch
    for event in client.take_world_events() { ... }   // 3. handle events
    for event in client.take_tick_events(&now) { ... } // 4. advance ticks
    // apply predicted state here
    client.send_all_packets(&world);                   // 5. flush outbound
}

Steps 1–5 must run in this order every frame. Call auth and then connect once before entering the loop.

Implementations§

Source§

impl<E: Copy + Eq + Hash + Send + Sync> Client<E>

Source

pub fn new<P: Into<Protocol>>(client_config: ClientConfig, protocol: P) -> Self

Creates a new client with the given config and protocol.

Call auth (optional) and then connect before entering the main loop.

Source

pub fn new_with_protocol_id( client_config: ClientConfig, protocol: Protocol, protocol_id: ProtocolId, ) -> Self

Creates a new client with an explicit protocol ID.

§Adapter use only

Bevy and macroquad adapters use this to inject a pre-computed ID. Prefer new in application code.

Source

pub fn entity_priority(&self, entity: E) -> EntityPriorityRef<'_, E>

Read-only handle to the priority state for entity on this client’s outbound connection.

Source

pub fn entity_priority_mut(&mut self, entity: E) -> EntityPriorityMut<'_, E>

Mutable handle to the priority state for entity on this client’s outbound connection. Lazy-creates an entry on first write.

Source

pub fn auth<M: Message>(&mut self, auth: M)

Stores the authentication message to send during the handshake.

Must be called before connect if the server requires authentication. The server receives this as an AuthEvent in its connection handler.

Source

pub fn auth_headers(&mut self, headers: Vec<(String, String)>)

Stores HTTP-style key-value headers to include in the WebRTC upgrade request.

Used by WebRTC transports that support header-based authentication or routing. Ignored by native UDP sockets.

Source

pub fn connect<S: Into<Box<dyn Socket>>>(&mut self, socket: S)

Opens the socket and begins the handshake with the server.

If auth was called, the auth payload is included in the handshake. After connecting, process events via the main loop until a ConnectionEvent arrives.

§Panics

Panics if the client has already initiated a connection. Check connection_status before calling.

Source

pub fn connection_status(&self) -> ConnectionStatus

Returns the client’s current connection lifecycle state.

Transitions: DisconnectedConnecting (after connect) → Connected (after handshake) → Disconnecting (after disconnect) → Disconnected.

Source

pub fn disconnect(&mut self)

Initiates a clean disconnect from the server.

Sends several disconnect packets to increase delivery probability, then begins the disconnection process. A DisconnectionEvent is emitted on the next take_world_events call.

§Panics

Panics if the client is not currently connected.

Source

pub fn socket_config(&self) -> &SocketConfig

Returns the socket configuration from the protocol.

Source

pub fn receive_all_packets(&mut self)

Reads all pending packets from the socket.

Must be called first in the client loop, before process_all_packets. Handles handshake progress, heartbeats, and buffers incoming data packets.

Source

pub fn process_all_packets<W: WorldMutType<E>>( &mut self, world: W, now: &Instant, )

Decodes all buffered packets and applies changes to the world.

Must be called after receive_all_packets and before take_world_events. Applies server-replicated entity spawn/update/despawn events and queues them for the next [take_world_events] call.

Source

pub fn take_world_events(&mut self) -> Events<E>

Drains and returns all accumulated world events since the last call.

Must be called after process_all_packets. The returned Events contains entity spawn/despawn/update notifications, message arrivals, connection/disconnection signals, and authority events. Not calling this causes the buffer to grow without bound.

Source

pub fn take_tick_events(&mut self, now: &Instant) -> TickEvents

Advances the tick clocks and returns any tick-boundary events.

Must be called after take_world_events. Returns a TickEvents containing client and server tick advances since the last call. Also de-jitters buffered packets on tick boundaries (unless the jitter buffer is in bypass mode).

Source

pub fn send_all_packets<W: WorldRefType<E>>(&mut self, world: W)

Flushes all queued messages and entity mutations to the server.

Must be called last in the client loop. Serialises outbound packets and hands them to the transport. Also handles handshake packet retransmission when not yet connected. If this is not called, the server never receives any updates.

Source

pub fn send_message<C: Channel, M: Message>( &mut self, message: &M, ) -> Result<(), NaiaClientError>

Queues a message to be sent to the server on the next send_all_packets call.

C is the channel type (ordering and reliability). M is the message type (must be registered in the Protocol). Messages sent before the connection is established are queued and delivered on connect.

§Errors

Returns an error if the channel does not allow client-to-server messages, or if the channel is TickBuffered (use send_tick_buffer_message instead).

Source

pub fn send_request<C: Channel, Q: Request>( &mut self, request: &Q, ) -> Result<ResponseReceiveKey<Q::Response>, NaiaClientError>

Sends a request to the server and returns a key for polling the response.

Use receive_response with the returned key to collect the server’s reply.

§Errors

Returns an error if the client is not currently connected.

§Panics

Panics if the channel is not bidirectional and reliable.

Source

pub fn send_response<S: Response>( &mut self, response_key: &ResponseSendKey<S>, response: &S, ) -> bool

Sends a response to the server’s request.

response_key is obtained from the RequestEvent that delivered the server’s original request. Returns true on success; false if the key is no longer valid (e.g. the connection was dropped).

Source

pub fn has_response<S: Response>( &self, response_key: &ResponseReceiveKey<S>, ) -> bool

Returns true if a response to the given request has arrived.

Non-destructive — does not consume the response. Call receive_response to retrieve and consume it.

Source

pub fn receive_response<S: Response>( &mut self, response_key: &ResponseReceiveKey<S>, ) -> Option<S>

Polls for and consumes a response to a previously sent client request.

Returns Some(response) once the server replies, or None if the response has not yet arrived or the key is invalid. The key is invalidated after a successful receive.

Source

pub fn send_tick_buffer_message<C: Channel, M: Message>( &mut self, tick: &Tick, message: &M, )

Queues a tick-buffered message stamped with the given client tick.

Use this for client input on a TickBuffered channel. The server receives the message when its tick counter reaches the stamped tick, enabling tick-accurate input replay.

§Panics

Panics if the channel does not have TickBuffered mode enabled.

Source

pub fn spawn_entity<W: WorldMutType<E>>( &mut self, world: W, ) -> EntityMut<'_, E, W>

Spawns a client-owned entity and returns a builder for configuring it.

The spawned entity starts as Private; call configure_replication on the returned EntityMut to publish it.

Requires that the protocol was built with enable_client_authoritative_entities().

§Panics

Panics if client-authoritative entities are not enabled in the protocol.

Source

pub fn has_resource<R: 'static>(&self) -> bool

Returns true if the client has a server-replicated resource of type R currently in scope.

Source

pub fn resource_entity<R: 'static>(&self) -> Option<E>

O(1): the world-entity carrying resource R on this client, or None if not currently in scope.

Source

pub fn is_resource_entity(&self, world_entity: &E) -> bool

True iff world_entity is the entity carrying any Replicated Resource currently in scope on this client.

Source

pub fn resources_count(&self) -> usize

Number of currently-mirrored Replicated Resources.

Source

pub fn resource_entities(&self) -> Vec<E>

Iterate over the world-entities of all currently-mirrored resources.

Source

pub fn entity<W: WorldRefType<E>>( &self, world: W, entity: &E, ) -> EntityRef<'_, E, W>

Returns a read-only handle to the entity.

§Panics

Panics if the entity does not exist in the world.

Source

pub fn entity_mut<W: WorldMutType<E>>( &mut self, world: W, entity: &E, ) -> EntityMut<'_, E, W>

Returns a mutable handle to the entity.

§Panics

Panics if the entity does not exist in the world, or if client-authoritative entities are not enabled in the protocol.

Source

pub fn entities<W: WorldRefType<E>>(&self, world: &W) -> Vec<E>

Returns all entities currently present in the world.

Source

pub fn enable_entity_replication(&mut self, entity: &E)

Registers the entity with the replication layer.

§Adapter use only

Called by the Bevy adapter when a Replicate component is inserted. Use spawn_entity in application code.

Source

pub fn disable_entity_replication(&mut self, entity: &E)

Unregisters the entity from the replication layer.

§Adapter use only

Called by the Bevy adapter when a Replicate component is removed.

Source

pub fn entity_replication_config(&self, world_entity: &E) -> Option<Publicity>

Returns the current Publicity for the entity, or None if the entity is not registered.

§Adapter use only

Use EntityRef::replication_config in application code.

Source

pub fn configure_entity_replication<W: WorldMutType<E>>( &mut self, world: &mut W, world_entity: &E, config: Publicity, )

Updates the replication config for a client-owned entity.

§Adapter use only

Application code should call entity_mut(...).configure_replication(config) instead.

§Panics

Panics if the entity is server-owned, not yet replicating, or if the entity is already Delegated.

Source

pub fn entity_authority_status( &self, world_entity: &E, ) -> Option<EntityAuthStatus>

Returns the current authority status for the entity from the client’s perspective, or None if the entity is not delegable.

§Adapter use only

Application code should inspect authority via EntityRef::authority.

Source

pub fn entity_request_authority( &mut self, world_entity: &E, ) -> Result<(), AuthorityError>

Sends an authority request to the server for the given delegated entity.

The server responds with either EntityAuthGrantedEvent or EntityAuthDeniedEvent. Only valid for entities with Delegated replication config.

§Adapter use only

Application code should call entity_mut(...).request_authority() instead.

Source

pub fn entity_release_authority( &mut self, world_entity: &E, ) -> Result<(), AuthorityError>

Releases the client’s authority over the given entity back to the server.

Only valid when this client holds Granted authority. The server resumes ownership after confirming the release.

§Adapter use only

Application code should call entity_mut(...).release_authority() instead.

Source

pub fn server_address(&self) -> Result<SocketAddr, NaiaClientError>

Returns the server’s socket address.

§Errors

Returns an error if the connection has not been established yet.

Source

pub fn rtt(&self) -> f32

Returns the rolling-average round-trip time (seconds) to the server.

Returns 0.0 if the connection has not been established yet.

Source

pub fn jitter(&self) -> f32

Returns the rolling-average jitter (seconds) measured for the server connection.

Returns 0.0 if the connection has not been established yet.

Source

pub fn client_tick(&self) -> Option<Tick>

Returns the client’s current sending tick, or None if not connected.

This is the tick at which the client is currently sending — use it to stamp TickBuffered messages for prediction.

Source

pub fn client_instant(&self) -> Option<GameInstant>

Returns the GameInstant corresponding to the client’s current sending tick, or None if not connected.

Source

pub fn server_tick(&self) -> Option<Tick>

Returns the server tick that the client is currently receiving, or None if not connected.

This lags slightly behind the server’s actual current tick due to network latency and the jitter buffer.

Source

pub fn server_instant(&self) -> Option<GameInstant>

Returns the GameInstant corresponding to the current server-receive tick, or None if not connected.

Source

pub fn tick_to_instant(&self, tick: Tick) -> Option<GameInstant>

Converts a tick counter value to the corresponding GameInstant, or None if not connected.

Source

pub fn tick_duration(&self) -> Option<Duration>

Returns the duration of a single tick as configured in the protocol, or None if not connected.

Source

pub fn client_interpolation(&self) -> Option<f32>

Returns the interpolation fraction [0.0, 1.0) for the current frame within the client sending tick.

Use this to lerp predicted entities between their state at the previous and current client ticks. Returns None if not connected.

Source

pub fn server_interpolation(&self) -> Option<f32>

Returns the interpolation fraction [0.0, 1.0) for the current frame within the server receive tick.

Use this to lerp authoritative server-replicated entities between their state at the previous and current server ticks. Returns None if not connected.

Source

pub fn outgoing_bandwidth(&self) -> f32

Returns the rolling-average outgoing bandwidth to the server (bytes/second).

Source

pub fn incoming_bandwidth(&self) -> f32

Returns the rolling-average incoming bandwidth from the server (bytes/second).

Source

pub fn connection_stats(&self) -> Option<ConnectionStats>

Returns a snapshot of per-connection diagnostics.

Returns None if not connected. Includes RTT (average in ms), jitter, packet-loss fraction, and send/recv bandwidth in kbps.

Source

pub fn despawn_entity_worldless(&mut self, world_entity: &E)

Despawns the entity from the replication layer without touching the world.

§Adapter use only

The Bevy adapter calls this when the ECS world has already removed the entity. Application code should despawn via the world, which triggers the adapter hook automatically.

§Panics

Panics if the entity is server-owned without delegation, or if the client does not hold Granted authority over a delegated entity.

Source

pub fn component_name(&self, component_kind: &ComponentKind) -> String

Returns the registered name of the component identified by component_kind; intended for debug logging.

Source

pub fn insert_component_worldless( &mut self, world_entity: &E, component: &mut dyn Replicate, )

Registers a component insertion with the replication layer without touching the world’s component storage.

§Adapter use only

The Bevy adapter calls this when the component already exists in the ECS world. Application code should insert components via the world.

Source

pub fn remove_component_worldless( &mut self, world_entity: &E, component_kind: &ComponentKind, )

Registers a component removal with the replication layer without touching the world’s component storage.

§Adapter use only

The Bevy adapter calls this when the component has already been removed from the ECS world.

Trait Implementations§

Source§

impl<E: Hash + Copy + Eq + Sync + Send> EntityAndGlobalEntityConverter<E> for Client<E>

Source§

fn global_entity_to_entity( &self, global_entity: &GlobalEntity, ) -> Result<E, EntityDoesNotExistError>

Resolves global_entity to the corresponding world-local entity E, or returns an error if not found.
Source§

fn entity_to_global_entity( &self, world_entity: &E, ) -> Result<GlobalEntity, EntityDoesNotExistError>

Resolves a world-local entity to its stable GlobalEntity identifier, or returns an error if not found.

Auto Trait Implementations§

§

impl<E> Freeze for Client<E>

§

impl<E> !RefUnwindSafe for Client<E>

§

impl<E> Send for Client<E>

§

impl<E> Sync for Client<E>

§

impl<E> Unpin for Client<E>
where E: Unpin,

§

impl<E> UnsafeUnpin for Client<E>

§

impl<E> !UnwindSafe for Client<E>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V