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>
impl<E: Copy + Eq + Hash + Send + Sync> Client<E>
Sourcepub fn new<P: Into<Protocol>>(client_config: ClientConfig, protocol: P) -> Self
pub fn new<P: Into<Protocol>>(client_config: ClientConfig, protocol: P) -> Self
Sourcepub fn new_with_protocol_id(
client_config: ClientConfig,
protocol: Protocol,
protocol_id: ProtocolId,
) -> Self
pub fn new_with_protocol_id( client_config: ClientConfig, protocol: Protocol, protocol_id: ProtocolId, ) -> Self
Sourcepub fn entity_priority(&self, entity: E) -> EntityPriorityRef<'_, E>
pub fn entity_priority(&self, entity: E) -> EntityPriorityRef<'_, E>
Read-only handle to the priority state for entity on this client’s
outbound connection.
Sourcepub fn entity_priority_mut(&mut self, entity: E) -> EntityPriorityMut<'_, E>
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.
Sourcepub fn auth_headers(&mut self, headers: Vec<(String, String)>)
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.
Sourcepub fn connect<S: Into<Box<dyn Socket>>>(&mut self, socket: S)
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.
Sourcepub fn connection_status(&self) -> ConnectionStatus
pub fn connection_status(&self) -> ConnectionStatus
Returns the client’s current connection lifecycle state.
Transitions: Disconnected → Connecting (after
connect) → Connected (after handshake) →
Disconnecting (after disconnect) →
Disconnected.
Sourcepub fn disconnect(&mut self)
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.
Sourcepub fn socket_config(&self) -> &SocketConfig
pub fn socket_config(&self) -> &SocketConfig
Returns the socket configuration from the protocol.
Sourcepub fn receive_all_packets(&mut self)
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.
Sourcepub fn process_all_packets<W: WorldMutType<E>>(
&mut self,
world: W,
now: &Instant,
)
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.
Sourcepub fn take_world_events(&mut self) -> Events<E>
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.
Sourcepub fn take_tick_events(&mut self, now: &Instant) -> TickEvents
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).
Sourcepub fn send_all_packets<W: WorldRefType<E>>(&mut self, world: W)
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.
Sourcepub fn send_message<C: Channel, M: Message>(
&mut self,
message: &M,
) -> Result<(), NaiaClientError>
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).
Sourcepub fn send_request<C: Channel, Q: Request>(
&mut self,
request: &Q,
) -> Result<ResponseReceiveKey<Q::Response>, NaiaClientError>
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.
Sourcepub fn send_response<S: Response>(
&mut self,
response_key: &ResponseSendKey<S>,
response: &S,
) -> bool
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).
Sourcepub fn has_response<S: Response>(
&self,
response_key: &ResponseReceiveKey<S>,
) -> bool
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.
Sourcepub fn receive_response<S: Response>(
&mut self,
response_key: &ResponseReceiveKey<S>,
) -> Option<S>
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.
Sourcepub fn send_tick_buffer_message<C: Channel, M: Message>(
&mut self,
tick: &Tick,
message: &M,
)
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.
Sourcepub fn spawn_entity<W: WorldMutType<E>>(
&mut self,
world: W,
) -> EntityMut<'_, E, W>
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.
Sourcepub fn has_resource<R: 'static>(&self) -> bool
pub fn has_resource<R: 'static>(&self) -> bool
Returns true if the client has a server-replicated resource of type
R currently in scope.
Sourcepub fn resource_entity<R: 'static>(&self) -> Option<E>
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.
Sourcepub fn is_resource_entity(&self, world_entity: &E) -> bool
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.
Sourcepub fn resources_count(&self) -> usize
pub fn resources_count(&self) -> usize
Number of currently-mirrored Replicated Resources.
Sourcepub fn resource_entities(&self) -> Vec<E>
pub fn resource_entities(&self) -> Vec<E>
Iterate over the world-entities of all currently-mirrored resources.
Sourcepub fn entity<W: WorldRefType<E>>(
&self,
world: W,
entity: &E,
) -> EntityRef<'_, E, W>
pub fn entity<W: WorldRefType<E>>( &self, world: W, entity: &E, ) -> EntityRef<'_, E, W>
Sourcepub fn entity_mut<W: WorldMutType<E>>(
&mut self,
world: W,
entity: &E,
) -> EntityMut<'_, E, W>
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.
Sourcepub fn entities<W: WorldRefType<E>>(&self, world: &W) -> Vec<E>
pub fn entities<W: WorldRefType<E>>(&self, world: &W) -> Vec<E>
Returns all entities currently present in the world.
Sourcepub fn enable_entity_replication(&mut self, entity: &E)
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.
Sourcepub fn disable_entity_replication(&mut self, entity: &E)
pub fn disable_entity_replication(&mut self, entity: &E)
Sourcepub fn entity_replication_config(&self, world_entity: &E) -> Option<Publicity>
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.
Sourcepub fn configure_entity_replication<W: WorldMutType<E>>(
&mut self,
world: &mut W,
world_entity: &E,
config: Publicity,
)
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.
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.
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.
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.
Sourcepub fn server_address(&self) -> Result<SocketAddr, NaiaClientError>
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.
Sourcepub fn rtt(&self) -> f32
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.
Sourcepub fn jitter(&self) -> f32
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.
Sourcepub fn client_tick(&self) -> Option<Tick>
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.
Sourcepub fn client_instant(&self) -> Option<GameInstant>
pub fn client_instant(&self) -> Option<GameInstant>
Returns the GameInstant corresponding to the client’s current sending
tick, or None if not connected.
Sourcepub fn server_tick(&self) -> Option<Tick>
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.
Sourcepub fn server_instant(&self) -> Option<GameInstant>
pub fn server_instant(&self) -> Option<GameInstant>
Returns the GameInstant corresponding to the current server-receive
tick, or None if not connected.
Sourcepub fn tick_to_instant(&self, tick: Tick) -> Option<GameInstant>
pub fn tick_to_instant(&self, tick: Tick) -> Option<GameInstant>
Converts a tick counter value to the corresponding GameInstant,
or None if not connected.
Sourcepub fn tick_duration(&self) -> Option<Duration>
pub fn tick_duration(&self) -> Option<Duration>
Returns the duration of a single tick as configured in the protocol,
or None if not connected.
Sourcepub fn client_interpolation(&self) -> Option<f32>
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.
Sourcepub fn server_interpolation(&self) -> Option<f32>
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.
Sourcepub fn outgoing_bandwidth(&self) -> f32
pub fn outgoing_bandwidth(&self) -> f32
Returns the rolling-average outgoing bandwidth to the server (bytes/second).
Sourcepub fn incoming_bandwidth(&self) -> f32
pub fn incoming_bandwidth(&self) -> f32
Returns the rolling-average incoming bandwidth from the server (bytes/second).
Sourcepub fn connection_stats(&self) -> Option<ConnectionStats>
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.
Sourcepub fn despawn_entity_worldless(&mut self, world_entity: &E)
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.
Sourcepub fn component_name(&self, component_kind: &ComponentKind) -> String
pub fn component_name(&self, component_kind: &ComponentKind) -> String
Returns the registered name of the component identified by component_kind; intended for debug logging.
Sourcepub fn insert_component_worldless(
&mut self,
world_entity: &E,
component: &mut dyn Replicate,
)
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.
Sourcepub fn remove_component_worldless(
&mut self,
world_entity: &E,
component_kind: &ComponentKind,
)
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>
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>
fn global_entity_to_entity( &self, global_entity: &GlobalEntity, ) -> Result<E, EntityDoesNotExistError>
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>
fn entity_to_global_entity( &self, world_entity: &E, ) -> Result<GlobalEntity, EntityDoesNotExistError>
entity to its stable GlobalEntity identifier, or returns an error if not found.