Struct Server

Source
pub struct Server<T: Transceiver, Ctx = ()> { /* private fields */ }
Expand description

The netcode server.

Responsible for accepting connections from clients and communicating with them using the netcode protocol.
The server should be run in a loop to process incoming packets, send updates to clients, and maintain stable connections.

§Example

let private_key = netcode::generate_key();
let protocol_id = 0x123456789ABCDEF0;
let addr = "127.0.0.1:41235";
let mut server = Server::new(addr, protocol_id, private_key).unwrap();

let start = Instant::now();
let tick_rate = Duration::from_secs_f64(1.0 / 60.0);

loop {
    server.update(start.elapsed().as_secs_f64());
    if let Some((received, from)) = server.recv() {
        // ...
    }
    thread::sleep(tick_rate);
}

Implementations§

Source§

impl Server<NetcodeSocket>

Source

pub fn new( bind_addr: impl ToSocketAddrs, protocol_id: u64, private_key: Key, ) -> Result<Self>

Create a new server with a default configuration.

For a custom configuration, use Server::with_config instead.

Source§

impl<Ctx> Server<NetcodeSocket, Ctx>

Source

pub fn with_config( bind_addr: impl ToSocketAddrs, protocol_id: u64, private_key: Key, cfg: ServerConfig<Ctx>, ) -> Result<Self>

Create a new server with a custom configuration.
Callbacks with context can be registered with the server to be notified when the server changes states.
See ServerConfig for more details.

§Example
use netcode::{Server, ServerConfig};
use std::net::{SocketAddr, Ipv4Addr};

let private_key = netcode::generate_key();
let protocol_id = 0x123456789ABCDEF0;
let addr = "127.0.0.1:40002";
let cfg = ServerConfig::with_context(42).on_connect(|idx, ctx| {
    assert_eq!(ctx, &42);
});
let server = Server::with_config(addr, protocol_id, private_key, cfg).unwrap();
Source§

impl<T: Transceiver, S> Server<T, S>

Source

pub fn with_config_and_transceiver( protocol_id: u64, private_key: Key, cfg: ServerConfig<S>, trx: T, ) -> Result<Self>

Creates a new server instance with the given configuration and transceiver.

This is useful if you want to use a custom transceiver implementation, in any other case you should use Server::new or Server::with_config.

§Examples
use netcode::{Server, ServerConfig, Transceiver};

struct MyTransceiver {
   // ...
};

impl Transceiver for MyTransceiver {
   // ...
}

let protocol_id = 0x1122334455667788;
let private_key = netcode::generate_key();
let cfg = ServerConfig::default();
let trx = MyTransceiver { /* .. */ };

let server = Server::with_config_and_transceiver(protocol_id, private_key, cfg, trx).unwrap();
Source

pub fn update(&mut self, time: f64)

Updates the server.

  • Updates the server’s elapsed time.
  • Receives and processes packets from clients, any received payload packets will be queued.
  • Sends keep-alive packets to connected clients.
  • Checks for timed out clients and disconnects them.

This method should be called regularly, probably at a fixed rate (e.g., 60Hz).

§Panics

Panics if the server can’t send or receive packets. For a non-panicking version, use try_update.

Source

pub fn try_update(&mut self, time: f64) -> Result<()>

The fallible version of update.

Returns an error if the server can’t send or receive packets.

Source

pub fn recv(&mut self) -> Option<(Vec<u8>, ClientIndex)>

Receives a packet from a client, if one is available in the queue.

The packet will be returned as a Vec<u8> along with the client index of the sender.

If no packet is available, None will be returned.

§Example
let start = Instant::now();
loop {
   let now = start.elapsed().as_secs_f64();
   server.update(now);
   let mut packet_buf = [0u8; netcode::MAX_PACKET_SIZE];
   while let Some((packet, from)) = server.recv() {
       // ...
   }
}
Source

pub fn send(&mut self, buf: &[u8], client_idx: ClientIndex) -> Result<()>

Sends a packet to a client.

The provided buffer must be smaller than MAX_PACKET_SIZE.

Source

pub fn send_all(&mut self, buf: &[u8]) -> Result<()>

Sends a packet to all connected clients.

The provided buffer must be smaller than MAX_PACKET_SIZE.

Source

pub fn token(&mut self, client_id: ClientId) -> ConnectTokenBuilder<SocketAddr>

Creates a connect token builder for a given client ID. The builder can be used to configure the token with additional data before generating the final token. The generate method must be called on the builder to generate the final token.

§Example
  
let private_key = netcode::generate_key();
let protocol_id = 0x123456789ABCDEF0;
let bind_addr = "0.0.0.0:0";
let mut server = Server::new(bind_addr, protocol_id, private_key).unwrap();

let client_id = 123u64;
let token = server.token(client_id)
    .expire_seconds(60)  // defaults to 30 seconds, negative for no expiry
    .timeout_seconds(-1) // defaults to 15 seconds, negative for no timeout
    .generate()
    .unwrap();

See ConnectTokenBuilder for more options.

Source

pub fn disconnect(&mut self, client_idx: ClientIndex) -> Result<()>

Disconnects a client.

The server will send a number of redundant disconnect packets to the client, and then remove its connection info.

Source

pub fn disconnect_all(&mut self) -> Result<()>

Disconnects all clients.

Source

pub fn addr(&self) -> SocketAddr

Gets the local SocketAddr this server is bound to.

Source

pub fn num_connected_clients(&self) -> usize

Gets the number of connected clients.

Source

pub fn client_id(&self, client_idx: ClientIndex) -> Option<ClientId>

Gets the ClientId of a client.

Source

pub fn client_addr(&self, client_idx: ClientIndex) -> Option<SocketAddr>

Gets the address of a client.

Auto Trait Implementations§

§

impl<T, Ctx> Freeze for Server<T, Ctx>
where T: Freeze, Ctx: Freeze,

§

impl<T, Ctx = ()> !RefUnwindSafe for Server<T, Ctx>

§

impl<T, Ctx> Send for Server<T, Ctx>
where T: Send, Ctx: Send,

§

impl<T, Ctx> Sync for Server<T, Ctx>
where T: Sync, Ctx: Sync,

§

impl<T, Ctx> Unpin for Server<T, Ctx>
where T: Unpin, Ctx: Unpin,

§

impl<T, Ctx = ()> !UnwindSafe for Server<T, Ctx>

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> Same for T

Source§

type Output = T

Should always be Self
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.