Skip to main content

Crate netcode

Crate netcode 

Source
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§

Client
A netcode client.
Server
A netcode dedicated server.

Enums§

ClientState
The state of a Client.
DisconnectReason
Why a client was disconnected from the server.
Error
Errors returned by this crate.
ServerEvent
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.

Type Aliases§

Key
A 256-bit encryption key.
UserData
User data carried from the connect token to the server, opaque to netcode.