Expand description
netcode is a secure client/server protocol for multiplayer games built on top of UDP.
This crate is a Rust implementation of the netcode 1.02 standard. It interoperates with the reference C implementation and other conforming implementations.
§Overview
A web backend authenticates each client and hands it a connect token over HTTPS. The client uses the connect token to establish a connection with a dedicated server over UDP. Once connected, the client and server exchange encrypted and signed packets.
§Example
use std::net::SocketAddr;
let private_key = netcode::generate_key();
let protocol_id = 0x1122334455667788;
let server_address: SocketAddr = "127.0.0.1:40000".parse().unwrap();
let mut server = netcode::Server::new(server_address, protocol_id, &private_key, 0.0).unwrap();
server.start(16).unwrap();
let client_address: SocketAddr = "0.0.0.0:0".parse().unwrap();
let mut client = netcode::Client::new(client_address, 0.0).unwrap();
let client_id = 1234;
let user_data = [0u8; netcode::USER_DATA_BYTES];
let connect_token = netcode::generate_connect_token(
&[server_address],
&[server_address],
30,
5,
client_id,
protocol_id,
&private_key,
&user_data,
)
.unwrap();
client.connect(&connect_token).unwrap();
let mut time = 0.0;
loop {
client.update(time);
server.update(time);
if client.state() == netcode::ClientState::Connected {
client.send_packet(&[1, 2, 3, 4]).unwrap();
}
while let Some((payload, _sequence)) = server.receive_packet(0) {
println!("server received {} byte packet", payload.len());
}
std::thread::sleep(std::time::Duration::from_secs_f64(1.0 / 60.0));
time += 1.0 / 60.0;
}Structs§
Enums§
- Client
State - The state of a
Client. - Disconnect
Reason - Why a client was disconnected from the server.
- Error
- Errors returned by this crate.
- Server
Event - A connection event on the server, drained with
Server::next_event.
Constants§
- CONNECT_
TOKEN_ BYTES - The size of a connect token in bytes.
- KEY_
BYTES - The size of an encryption key in bytes.
- MAC_
BYTES - The size of an AEAD authentication tag (HMAC) in bytes.
- MAX_
CLIENTS - The maximum number of client slots on a server.
- MAX_
PAYLOAD_ BYTES - The maximum size of a payload packet in bytes.
- MAX_
SERVERS_ PER_ CONNECT - The maximum number of server addresses in a connect token.
- USER_
DATA_ BYTES - The size of the per-client user data block carried in connect tokens.
Functions§
- generate_
connect_ token - Generates a connect token.
- generate_
key - Generates a cryptographically secure random 256-bit key.