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>
impl Server<NetcodeSocket>
Sourcepub fn new(
bind_addr: impl ToSocketAddrs,
protocol_id: u64,
private_key: Key,
) -> Result<Self>
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>
impl<Ctx> Server<NetcodeSocket, Ctx>
Sourcepub fn with_config(
bind_addr: impl ToSocketAddrs,
protocol_id: u64,
private_key: Key,
cfg: ServerConfig<Ctx>,
) -> Result<Self>
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>
impl<T: Transceiver, S> Server<T, S>
Sourcepub fn with_config_and_transceiver(
protocol_id: u64,
private_key: Key,
cfg: ServerConfig<S>,
trx: T,
) -> Result<Self>
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();
Sourcepub fn update(&mut self, time: f64)
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
.
Sourcepub fn try_update(&mut self, time: f64) -> Result<()>
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.
Sourcepub fn recv(&mut self) -> Option<(Vec<u8>, ClientIndex)>
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() {
// ...
}
}
Sourcepub fn send(&mut self, buf: &[u8], client_idx: ClientIndex) -> Result<()>
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
.
Sourcepub fn send_all(&mut self, buf: &[u8]) -> Result<()>
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
.
Sourcepub fn token(&mut self, client_id: ClientId) -> ConnectTokenBuilder<SocketAddr>
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.
Sourcepub fn disconnect(&mut self, client_idx: ClientIndex) -> Result<()>
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.
Sourcepub fn disconnect_all(&mut self) -> Result<()>
pub fn disconnect_all(&mut self) -> Result<()>
Disconnects all clients.
Sourcepub fn addr(&self) -> SocketAddr
pub fn addr(&self) -> SocketAddr
Gets the local SocketAddr
this server is bound to.
Sourcepub fn num_connected_clients(&self) -> usize
pub fn num_connected_clients(&self) -> usize
Gets the number of connected clients.
Sourcepub fn client_id(&self, client_idx: ClientIndex) -> Option<ClientId>
pub fn client_id(&self, client_idx: ClientIndex) -> Option<ClientId>
Gets the ClientId
of a client.
Sourcepub fn client_addr(&self, client_idx: ClientIndex) -> Option<SocketAddr>
pub fn client_addr(&self, client_idx: ClientIndex) -> Option<SocketAddr>
Gets the address of a client.