Expand description
Online play: host a game or join one over the internet or the local network.
Available as ctx.net.
One player (or a dedicated server, see Engine::run_server)
hosts, the others join. Everyone sends Packets: a kind and a few values. What
arrives shows up as NetEvents for one frame, like key presses.
use audio_code::prelude::*;
fn main() -> audio_code::Result<()> {
audio_code::run("Chat", |ctx| {
if ctx.once("start") {
ctx.net.set_name("Anna");
ctx.net.join("localhost"); // or: ctx.net.host(net::DEFAULT_PORT)
}
for player in ctx.net.joined() {
ctx.speak(format!("Connected to {}", ctx.net.name(player)));
}
if ctx.pressed(Key::Space) {
ctx.net.send_all(Packet::new("chat").with("Hello!"));
}
for (from, packet) in ctx.net.received("chat") {
ctx.speak(format!("{}: {}", ctx.net.name(from), packet.text(0)));
}
for (_, reason) in ctx.net.left() {
ctx.speak(ctx.lang.describe_reason(&reason));
}
})
}§What the engine does for you
- Connecting, the handshake and all sending and receiving run on background threads. The game never waits for the network.
- Only clients of the same game (the
Enginetitle) and the same version (Net::set_version) get in. Others are turned away withReason::WrongGame/Reason::WrongVersion. - Both sides ping each other every second (
Net::ping). A connection that hears nothing for 10 seconds is closed withReason::TimedOut. - Packets arrive complete, unchanged and in the order they were sent.
- Mistakes do not crash: sending while offline does nothing, joining a wrong address
ends with a
NetEvent::Disconnectedthat says why.
§WebSockets and encryption
Connections are WebSockets, so they pass firewalls and web proxies that only let web
traffic through, and a server can sit behind a web server such as nginx or Caddy.
Net::join takes plain addresses ("example.com", "10.0.0.2:7777") as well as
ws:// and wss:// URLs.
Everything is always encrypted, without any setup: both sides make fresh keys for
every connection (X25519) and encrypt every message (XChaCha20-Poly1305). Nobody who
listens in can read names, chat or game data, and changed messages are detected. This
does not prove who the server is, though: someone who can redirect the traffic could
pose as it. To rule that out, put the server behind a web server with a real TLS
certificate and join with wss:// (feature tls, on by default).
Structs§
- Net
- The network connection:
ctx.net. See the module docs. - Packet
- One message between players: a kind (what it is about) and a list of values.
- PeerId
- A connected player. On a client the server is
PeerId::SERVER.
Enums§
- Arg
- One value inside a
Packet. Made automatically byPacket::withfrom numbers,bool, text,Vec2,Vec3,PeerIdand byte vectors. - NetEvent
- Something that happened on the network this frame.
- Reason
- Why a connection ended. Speak it with
ctx.lang.describe_reason(&reason).
Constants§
- DEFAULT_
PORT - The port used when none is given:
ctx.net.join("example.com")connects to it.