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
+208
View File
@@ -0,0 +1,208 @@
## The server's end of the transport: listens with ENet, takes each new connection
## through the handshake, and reports who joined and who left. It decides nothing about
## the match; whoever owns it reads `events` after each poll().
##
## A connection is a guest until its HELLO is accepted. Guests can't do anything else,
## get one try, and are dropped if they stay silent past the handshake timeout. Player
## handles are positive, count up from 1 and are never reused while the server runs.
class_name NetServer
extends RefCounted
## Milliseconds a new connection has to send its HELLO.
var handshake_timeout_msec: int = 5000
## ENet drops a peer that acknowledges nothing for between these two times.
var peer_timeout_min_msec: int = 5000
var peer_timeout_max_msec: int = 15000
## Players allowed at once. Further clients are told the server is full.
var max_players: int = Tuning.SOLO_PLAYERS
## Sent to each client in its WELCOME, so it can generate the same island.
var match_seed: int = 0
## What happened during the last poll(): {"type": "joined", "handle", "name"},
## {"type": "left", "handle", "name", "reason"} and {"type": "refused", "reason"}.
var events: Array[Dictionary] = []
## Malformed or unexpected packets dropped so far.
var bad_packets: int = 0
var _host: ENetConnection = null
## Peers that haven't finished the handshake: ENetPacketPeer -> msec they connected.
var _guests: Dictionary = {}
## Peers being turned away: ENetPacketPeer -> the reason, until ENet reports them gone.
var _leaving: Dictionary = {}
## Handle -> {"peer": ENetPacketPeer, "name": String}.
var _players: Dictionary = {}
## ENetPacketPeer -> handle.
var _handle_of: Dictionary = {}
var _next_handle: int = 1
## Starts listening on UDP `port` (0 picks a free one) on `address`. Returns OK or the
## error, and leaves the server closed on failure.
func listen(port: int, address: String = "*") -> Error:
close()
var host: ENetConnection = ENetConnection.new()
# Room for a few guests beyond the player limit, so a full server can say so.
var error: Error = host.create_host_bound(address, port, max_players + 8, NetProtocol.CHANNEL_COUNT)
if error != OK:
return error
_host = host
return OK
func is_listening() -> bool:
return _host != null
## The UDP port in use, or 0 when closed.
func port() -> int:
return _host.get_local_port() if _host != null else 0
func player_count() -> int:
return _players.size()
func guest_count() -> int:
return _guests.size()
func handles() -> Array[int]:
var result: Array[int] = []
for handle: int in _players:
result.append(handle)
result.sort()
return result
## The accepted name of a player, or an empty string.
func name_of(handle: int) -> String:
return String(_players[handle]["name"]) if _players.has(handle) else ""
## Services the socket: accepts connections, runs handshakes, notices departures.
## Call it every frame. `now_msec` is for tests; it defaults to the engine's clock.
func poll(now_msec: int = -1) -> void:
events.clear()
if _host == null:
return
var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec()
while true:
var event: Array = _host.service(0)
var kind: int = event[0]
if kind == ENetConnection.EVENT_NONE or kind == ENetConnection.EVENT_ERROR:
break
var peer: ENetPacketPeer = event[1]
match kind:
ENetConnection.EVENT_CONNECT:
peer.set_timeout(0, peer_timeout_min_msec, peer_timeout_max_msec)
_guests[peer] = now
ENetConnection.EVENT_DISCONNECT:
_gone(peer, int(event[2]))
ENetConnection.EVENT_RECEIVE:
_received(peer, int(event[3]), peer.get_packet())
for peer: ENetPacketPeer in _guests.keys():
if now - int(_guests[peer]) >= handshake_timeout_msec:
_refuse(peer, NetProtocol.REASON_HANDSHAKE_TIMEOUT)
## Sends `bytes` to a player. Returns false if they aren't connected.
func send(handle: int, channel: int, bytes: PackedByteArray, reliable: bool) -> bool:
if not _players.has(handle):
return false
var peer: ENetPacketPeer = _players[handle]["peer"]
var flags: int = ENetPacketPeer.FLAG_RELIABLE if reliable else ENetPacketPeer.FLAG_UNSEQUENCED
return peer.send(channel, bytes, flags) == OK
## Removes a player, telling them why. They are reported as "left" at once.
func kick(handle: int, reason: int = NetProtocol.REASON_KICKED) -> bool:
if not _players.has(handle):
return false
var peer: ENetPacketPeer = _players[handle]["peer"]
events.append({"type": "left", "handle": handle, "name": name_of(handle), "reason": reason})
_players.erase(handle)
_handle_of.erase(peer)
_leaving[peer] = reason
peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE)
peer.peer_disconnect_later(reason)
return true
## Stops listening. Everyone connected is told the server shut down.
func close() -> void:
if _host == null:
return
for peer: ENetPacketPeer in _guests.keys() + _handle_of.keys() + _leaving.keys():
if peer.is_active():
peer.peer_disconnect_now(NetProtocol.REASON_SHUTDOWN)
_host.flush()
_host.destroy()
_host = null
_guests.clear()
_leaving.clear()
_players.clear()
_handle_of.clear()
func _received(peer: ENetPacketPeer, channel: int, bytes: PackedByteArray) -> void:
if _leaving.has(peer):
return
if _handle_of.has(peer):
# Game traffic arrives with N2. A second HELLO, or anything else, is dropped.
bad_packets += 1
return
if not _guests.has(peer):
return
var hello: Dictionary = NetProtocol.decode_hello(bytes) if channel == NetProtocol.CHANNEL_CONTROL else {}
if hello.is_empty():
bad_packets += 1
_refuse(peer, NetProtocol.REASON_BAD_HELLO)
elif int(hello["version"]) != NetProtocol.VERSION:
_refuse(peer, NetProtocol.REASON_VERSION)
elif _players.size() >= max_players:
_refuse(peer, NetProtocol.REASON_FULL)
else:
_guests.erase(peer)
var handle: int = _next_handle
_next_handle += 1
var player_name: String = _unique_name(String(hello["name"]))
_players[handle] = {"peer": peer, "name": player_name}
_handle_of[peer] = handle
peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_welcome(handle, match_seed, max_players, player_name), ENetPacketPeer.FLAG_RELIABLE)
events.append({"type": "joined", "handle": handle, "name": player_name})
## Turns a guest away: tells it why, then disconnects once that has been delivered.
func _refuse(peer: ENetPacketPeer, reason: int) -> void:
_guests.erase(peer)
_leaving[peer] = reason
events.append({"type": "refused", "reason": reason})
peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE)
peer.peer_disconnect_later(reason)
func _gone(peer: ENetPacketPeer, data: int) -> void:
_guests.erase(peer)
_leaving.erase(peer)
if not _handle_of.has(peer):
return
var handle: int = _handle_of[peer]
# A client that says goodbye sends REASON_LEFT; one that just vanishes sends nothing.
var reason: int = NetProtocol.REASON_LEFT if data == NetProtocol.REASON_LEFT else NetProtocol.REASON_LOST
events.append({"type": "left", "handle": handle, "name": name_of(handle), "reason": reason})
_players.erase(handle)
_handle_of.erase(peer)
## `wanted`, or `wanted` with a number after it if someone here already has that name.
func _unique_name(wanted: String) -> String:
var taken: Dictionary = {}
for handle: int in _players:
taken[String(_players[handle]["name"]).to_lower()] = true
if not taken.has(wanted.to_lower()):
return wanted
for number: int in range(2, max_players + 2):
var suffix: String = " %d" % number
var candidate: String = wanted.substr(0, NetProtocol.NAME_MAX_CHARS - suffix.length()).strip_edges() + suffix
if not taken.has(candidate.to_lower()):
return candidate
return wanted