N1: Transport and connection handshake

ENet over UDP, used directly through ENetConnection, with a handshake before a
connection counts as a player.

- NetProtocol: HELLO, WELCOME and REJECT layouts, the protocol version, name
  cleaning, the reasons a connection ends and a sentence for the player about
  each. Decoders return nothing for malformed input and never raise an error.
- NetServer: listens, takes each guest through the handshake, and reports
  joined, left and refused. It refuses a different protocol version, a full
  server, a malformed HELLO and a guest that stays silent, each with its own
  reason. Handles are never reused; duplicate names get a number.
- NetClient: connects, introduces itself, and ends up joined or closed with a
  reason. Leaving says goodbye so the server knows at once; a client that
  vanishes is dropped by ENet's timeout.
- Tests run a real server and clients over loopback UDP, with bare ENet peers
  sending malformed and random packets.

The headless server doesn't listen yet; N2 connects this to the match.

Closes #32

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 05:51:12 -05:00
co-authored by Claude Opus 5.5
parent 1d6a24ab64
commit 98a1a05dc8
12 changed files with 1009 additions and 0 deletions
+167
View File
@@ -0,0 +1,167 @@
## The client's end of the transport: connects to a server with ENet, introduces itself
## and reports whether it was let in. Call poll() every frame and read `state`.
class_name NetClient
extends RefCounted
const IDLE: int = 0
## Waiting for the server to answer at all.
const CONNECTING: int = 1
## Connected; HELLO sent, waiting for WELCOME or REJECT.
const HANDSHAKING: int = 2
const JOINED: int = 3
## Over. `close_reason` says why.
const CLOSED: int = 4
const STATE_NAMES: Array[String] = ["idle", "connecting", "handshaking", "joined", "closed"]
## Milliseconds to wait for the server to answer, and then for its verdict.
var connect_timeout_msec: int = 5000
var handshake_timeout_msec: int = 5000
var peer_timeout_min_msec: int = 5000
var peer_timeout_max_msec: int = 15000
## The protocol version to claim. Only tests change it.
var protocol_version: int = NetProtocol.VERSION
var state: int = IDLE
## A NetProtocol.REASON_* once closed.
var close_reason: int = NetProtocol.REASON_NONE
## The server's protocol version, once it has said.
var server_version: int = 0
## From the server's WELCOME.
var handle: int = 0
var player_name: String = ""
var match_seed: int = 0
var max_players: int = 0
var tick_rate: int = 0
var _host: ENetConnection = null
var _peer: ENetPacketPeer = null
var _wanted_name: String = ""
var _since_msec: int = 0
func state_name() -> String:
return STATE_NAMES[state]
## Starts connecting. Returns OK if the attempt began; the outcome comes through poll().
func connect_to(address: String, port: int, wanted_name: String, now_msec: int = -1) -> Error:
_drop()
state = IDLE
close_reason = NetProtocol.REASON_NONE
server_version = 0
handle = 0
var host: ENetConnection = ENetConnection.new()
var error: Error = host.create_host(1, NetProtocol.CHANNEL_COUNT)
if error != OK:
return error
var peer: ENetPacketPeer = host.connect_to_host(address, port, NetProtocol.CHANNEL_COUNT)
if peer == null:
host.destroy()
return ERR_CANT_CONNECT
_host = host
_peer = peer
_wanted_name = wanted_name
_since_msec = now_msec if now_msec >= 0 else Time.get_ticks_msec()
state = CONNECTING
return OK
func poll(now_msec: int = -1) -> void:
if _host == null:
return
var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec()
while _host != null:
var event: Array = _host.service(0)
var kind: int = event[0]
if kind == ENetConnection.EVENT_NONE or kind == ENetConnection.EVENT_ERROR:
break
match kind:
ENetConnection.EVENT_CONNECT:
_peer.set_timeout(0, peer_timeout_min_msec, peer_timeout_max_msec)
_peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_hello(_wanted_name, protocol_version), ENetPacketPeer.FLAG_RELIABLE)
state = HANDSHAKING
_since_msec = now
ENetConnection.EVENT_RECEIVE:
_received(int(event[3]), _peer.get_packet())
ENetConnection.EVENT_DISCONNECT:
var data: int = int(event[2])
var reason: int = close_reason
if reason == NetProtocol.REASON_NONE:
reason = data if data > NetProtocol.REASON_NONE and data <= NetProtocol.REASON_KICKED \
else (NetProtocol.REASON_NO_ANSWER if state == CONNECTING else NetProtocol.REASON_LOST)
_close(reason)
if state == CONNECTING and now - _since_msec >= connect_timeout_msec:
_close(NetProtocol.REASON_NO_ANSWER)
elif state == HANDSHAKING and now - _since_msec >= handshake_timeout_msec:
_close(NetProtocol.REASON_NO_ANSWER)
## Sends `bytes` to the server once joined. Returns false otherwise.
func send(channel: int, bytes: PackedByteArray, reliable: bool) -> bool:
if state != JOINED:
return false
return _peer.send(channel, bytes, ENetPacketPeer.FLAG_RELIABLE if reliable else ENetPacketPeer.FLAG_UNSEQUENCED) == OK
## Says goodbye and closes. The server learns at once rather than by timeout.
func leave() -> void:
if _host == null:
return
if _peer != null and _peer.is_active():
_peer.peer_disconnect_now(NetProtocol.REASON_LEFT)
_host.flush()
_close(NetProtocol.REASON_LEFT)
## A sentence for the player about where the connection stands.
func status_text() -> String:
match state:
CONNECTING:
return "Connecting..."
HANDSHAKING:
return "Joining..."
JOINED:
return "Joined as %s." % player_name
CLOSED:
return NetProtocol.reason_text(close_reason, server_version, protocol_version)
return "Not connected."
func _received(channel: int, bytes: PackedByteArray) -> void:
if channel != NetProtocol.CHANNEL_CONTROL or bytes.is_empty():
return
if state == HANDSHAKING and bytes[0] == NetProtocol.MSG_WELCOME:
var welcome: Dictionary = NetProtocol.decode_welcome(bytes)
if welcome.is_empty() or int(welcome["version"]) != protocol_version:
server_version = int(welcome.get("version", 0))
_peer.peer_disconnect_now(NetProtocol.REASON_LEFT)
_host.flush()
_close(NetProtocol.REASON_VERSION if not welcome.is_empty() else NetProtocol.REASON_BAD_HELLO)
return
server_version = int(welcome["version"])
handle = int(welcome["handle"])
player_name = String(welcome["name"])
match_seed = int(welcome["seed"])
max_players = int(welcome["max_players"])
tick_rate = int(welcome["tick_rate"])
state = JOINED
elif bytes[0] == NetProtocol.MSG_REJECT:
var reject: Dictionary = NetProtocol.decode_reject(bytes)
if reject.is_empty():
return
# Remember why; the server's disconnect follows and closes the connection.
server_version = int(reject["server_version"])
close_reason = int(reject["reason"])
func _close(reason: int) -> void:
_drop()
state = CLOSED
close_reason = reason
func _drop() -> void:
if _host != null:
_host.destroy()
_host = null
_peer = null