MultiConnectionUDPServer
A UDP server that multiplexes all traffic for any number of clients over a single well-known "common" socket (COMMON_LISTEN_PORT).
A client registers by sending Iam <name> (optionally Iam <name> <credential> with an opaque trailing token) to the common port from a socket it keeps open. The handshake stays plain UTF-8 text. The server itself refuses a malformed Iam - a missing or empty name, or a credential slot that is present but empty (Iam x, Iam bob tok) - with REFUSED malformed, whatever the state of its origin and without consulting admit. It screens every other new handshake through admit and either replies - from that same socket, addressed straight back to the datagram's source address and port - REGISTERED 2 (the accepted verb plus TransportWireFormat.FRAMED_PROTOCOL_VERSION, the framed-transport wire major), or refuses it with REFUSED <reason> (registering nothing, firing no onClientConnect). A cross-major peer fails its handshake() cleanly on the version token; both ends must be on webtools-udp 2.0.0+. From then on every datagram in either direction is framed - it leads with a 1-byte DatagramType tag (TransportWireFormat): 0x80 keepalive, 0x81/ 0x82 link-quality probe, 0x90 unreliable application data. The server addresses every datagram back to the client's observed post-NAT source. Because the server only ever transmits on a 5-tuple the client already opened, the data path traverses NAT and the server binds no per-client ports.
A client sends a bare 0x80 datagram on an idle interval (~20 s recommended) to keep its NAT mapping warm; the server consumes inbound 0x80 without dispatching it, but - when idle detection is enabled (see below) - an inbound 0x80, like any other datagram from that client, refreshes its liveness timestamp.
This class is abstract because it does not itself decide what to do once a client has finished the handshake - subclasses implement onClientConnect (e.g. call Connection.actuate, track the connection, notify the application).
The handshake rules live in HandshakeProtocol (pure) and HandshakeCoordinator (the state machine + inbound router); this class binds them to a real socket.
Handshake screening & credentials
Override admit to accept or refuse a handshake before it is registered. The default admits every well-formed Iam, which for a well-formed line is identical to the behaviour before webtools-udp 1.4.0. An Iam is well-formed unless its name slot is missing or empty, or its credential slot is present but empty. Since webtools-udp 2.0.0a the server refuses a malformed one itself (REFUSED malformed, an informative reason that a client must not branch on) before admit is consulted, so admit never sees an empty name and sees credential as "" only when the client sent none; an earlier server registered the empty-name and empty-credential shapes and left a bare Iam unanswered. The refusal is sent even to an origin that already holds a registration. That registration is not torn down, superseded or re-screened, and no onClientDisconnect fires; like any inbound datagram from a registered origin, the line does refresh its idle-detection stamp when idleTimeoutMillis is positive (see "Connection liveness" below). A peer that is mid-session can therefore receive the unframed REFUSED. admit returns Admission.Admitted or Admission.Refused(reason); on a refusal the server sends REFUSED <reason> back to the Iam origin, mints no Connection, adds no registration, and does not call onClientConnect - the client surfaces it as a typed HandshakeRefusedException. This removes the old "reply REGISTERED, then silently drop" workaround for capacity/auth refusals. A client may carry an opaque, whitespace-free <credential> token in its Iam line (Iam <name> <credential>); it is passed to admit verbatim, never interpreted by the library, and rides in cleartext. admit runs inline on the common listener thread, so it must return promptly.
Binary application payloads
Post-handshake application data may be raw bytes: Connection.push takes a ByteArray, Connection.actuateBytes / startBytes register a raw-bytes inbound handler, and pushToAll has a ByteArray overload. The transport wraps the payload in an 0x90 unreliable frame and strips it before delivery; delivery is an exact-length copy of that payload - no UTF-8 decode, no .trim(). Inbound routing is a switch on the 0x90 / 0x8x DatagramType tag, so any payload bytes ride intact - there is no reserved first byte and the pre-2.0 "lead with 0x00 / >= 0x80" rule is gone. An inbound datagram over 65507 bytes is delivered truncated, not rejected; on send (Connection.push / pushToAll), a payload over the OS datagram limit fails the Result (cause logged) rather than being sent. Keep frames under the path MTU (~1200 bytes) for real-network use.
The receive buffer size is a constructor parameter receiveBufferBytes, defaulting to DEFAULT_RECEIVE_BUFFER_BYTES (65507) so that by default no well-formed datagram is ever truncated on receive. A datagram larger than the configured size is delivered truncated, not rejected; when a datagram fills a sub-maximum buffer a WARN is logged. The "over 65507 bytes is delivered truncated" wording above stays accurate for the default configuration.
Construction side effects
Instantiating a subclass binds the OS UDP port COMMON_LISTEN_PORT and starts a daemon listener thread plus a single daemon dispatch thread. Construction throws java.net.SocketException (typically java.net.BindException) if that port is already in use, so only one instance can exist per JVM/host at a time. Call stop to release the port; the instance is single-use afterwards. Construction throws IllegalArgumentException if receiveBufferBytes is outside MIN_RECEIVE_BUFFER_BYTES..MAX_UDP_PAYLOAD_BYTES, or if idleTimeoutMillis is negative, or if reliableMaxMessageBytes is outside 1..UdpChannel.MAX_RELIABLE_MESSAGE_BYTES. A positive idleTimeoutMillis also starts the mcups-liveness daemon thread.
Parameters
size of the datagram receive buffer, MIN_RECEIVE_BUFFER_BYTES..MAX_UDP_PAYLOAD_BYTES; defaults to DEFAULT_RECEIVE_BUFFER_BYTES (65507) so no well-formed datagram is truncated
opt-in idle-connection threshold in milliseconds; 0 (the default, DISABLED_IDLE_TIMEOUT) disables idle detection entirely - no extra thread, no per-datagram work. Must be >= 0; a negative value throws IllegalArgumentException; 0 disables detection.
the reliable-channel application-payload cap, in bytes; defaults to UdpChannel.DEFAULT_MAX_RELIABLE_MESSAGE_BYTES (1024) and must be in 1..UdpChannel.MAX_RELIABLE_MESSAGE_BYTES (8192) - v1 does not fragment, so a larger reliable send fails with ReliableMessageTooLargeException
Connection liveness
With a positive idleTimeoutMillis, every registered connection carries the monotonic time of its last inbound datagram of any kind (application data, a 0x80 keepalive, a probe, a handshake line - even one that is dropped), and a dedicated mcups-liveness daemon thread periodically reports any connection idle beyond the threshold via onClientDisconnect with DisconnectReason.TIMEOUT. This is notify-only: the registration stays in place and addressable by pushToAll until the application calls Connection.terminate itself. A same-name supersede (DisconnectReason.SUPERSEDED) and an application Connection.terminate (DisconnectReason.TERMINATED) also flow through onClientDisconnect. stop teardown does not.
Scheduled keepalive
Opt-in and per-connection: Connection.startKeepAlive(intervalMillis) arms an idle-aware background keepalive that sends one 0x80 datagram to that client every ~intervalMillis of output silence (application traffic defers it), and Connection.stopKeepAlive / Connection.terminate / stop cancel it. The one-shot Connection.keepAlive primitive is unchanged. Server -> client keepalives refresh only endpoint-independent (cone) NAT mappings - the authoritative keepalive is still the client's own. No wire-format change.
Link quality (RTT & packet loss)
Opt-in and per-connection: Connection.startProbe(intervalMillis) arms a periodic transport-level 0x81/0x82 probe round trip (an 8-byte big-endian sequence) toward that client, yielding a smoothed RTT, an RTT-variance (jitter proxy), and a windowed packet-loss ratio as a single LinkQuality snapshot readable via Connection.linkQuality (null until the first 0x82 resolves). Off by default (one mcups-probe daemon thread, created lazily on the first Connection.startProbe); cancelled by Connection.stopProbe / Connection.terminate / stop. The server also answers any inbound 0x81 probe from a registered origin with an 0x82 reply inline on the listener thread, so a client can measure even if no server-side probe is armed. 0x81 / 0x82 are transport-consumed on both sides, and packetLossRatio is lagging and windowed - not a fast congestion signal. See the sequence diagram in docs/plans/13-link-quality-probe/plan.md §2.9.
Reliable-ordered channel
connection.channel(DeliveryMode.RELIABLE_ORDERED) (or the convenience startReliable / pushToAllReliable) sends acked, retransmitted, in-order 0xA0/0xA1 traffic to a client - see UdpChannel and DeliveryMode for the full contract, including the size cap (reliableMaxMessageBytes), the in-flight-window backpressure (ReliableWindowFullException), and the inherent head-of-line blocking. Each connection's engine is created lazily, on the first reliable send to that peer, the first startReliable / channel(RELIABLE_ORDERED).actuate* binding for it, or the first inbound 0xA0/0xA1 on channel 0x00 from it, whichever comes first - obtaining the handle alone creates nothing, and a frame on any other channel is dropped without creating one. One mcups-retransmit daemon thread backs every connection's retransmit tick.
Concurrency
One long-lived daemon listener thread (mcups-listener) only demultiplexes: receive() -> switch on the DatagramType tag (or an unframed Iam) -> run the socket-free handshake state machine inline, drop a keepalive/probe, or hand the stripped 0x90 payload to the dispatch executor. The admit screen runs inline on this listener thread too (like onClientConnect), so a slow admit stalls demultiplexing for every client. A third daemon thread - mcups-liveness, a ScheduledExecutorService - exists only when idleTimeoutMillis> 0; it runs the idle-connection sweep and never runs application code (the onClientDisconnect hook is handed to mcups-dispatch). A fourth daemon thread - mcups-keepalive, also a ScheduledExecutorService - exists only once a consumer calls Connection.startKeepAlive; it sends 0x80 keepalive datagrams and runs no application code. It is a dedicated executor, not the mcups-liveness one: liveness exists only for idleTimeoutMillis > 0 and has a different cadence and lifecycle. See the scheduled-keepalive sequence diagram in docs/plans/12-scheduled-keepalive/plan.md §2.8. A fifth daemon thread - mcups-probe, also a ScheduledExecutorService - exists only once a consumer calls Connection.startProbe; it sends 0x81 probe datagrams and runs no application code, and is again a dedicated executor so the probe and keepalive lifecycles stay independent. See docs/plans/13-link-quality-probe/plan.md §2.9. A sixth daemon thread - mcups-retransmit, also a ScheduledExecutorService - exists only once a reliable channel is opened (by either side); it retransmits unacked 0xA0 frames and emits standalone 0xA1 acks, and runs no application code - delivery itself still goes through mcups-dispatch.
The dispatch executor is a single daemon thread (mcups-dispatch) that invokes Connection message handlers, so per-client message order is preserved and a slow handler cannot stall the listener or the handshake. Accepted trade-off: a slow handler delays delivery to other clients - handlers must return promptly. The common socket is received on only by the listener thread but sent on from any thread (the JDK permits a concurrent send during a receive); the registration list is copy-on-write.
See the sequence diagram in docs/plans/1-nat-traversal/plan-tier-2.md §2.1 for the canonical end-to-end flow, and docs/plans/10-connection-liveness/plan.md §2.8 for the idle-sweep sequence.
See docs/webtools-udp-protocol.md for the complete wire reference and docs/webtools-udp-architecture.md for the complete thread/lifecycle picture this KDoc only summarises.
Types
The server's constants: COMMON_LISTEN_PORT, the receive-buffer bounds and default (MAX_UDP_PAYLOAD_BYTES, MIN_RECEIVE_BUFFER_BYTES, DEFAULT_RECEIVE_BUFFER_BYTES) and DISABLED_IDLE_TIMEOUT.
Functions
Screens an incoming Iam handshake before it is accepted. The default admits every well-formed handshake - today's behaviour. A malformed Iam (a missing or empty name, or a credential slot that is present but empty) never reaches here: the server answers it REFUSED malformed first, from any origin, so name is never empty and credential is "" only when the client sent none. Override to validate credential (an opaque token the client supplied, empty if it sent none) or to refuse for application reasons (over capacity, banned): return Admission.Refused and the client receives REFUSED <reason> as a typed HandshakeRefusedException, with nothing registered and no onClientConnect call. This replaces the old "reply REGISTERED then silently drop the client" pattern for a connect-time refusal.
Called once a client has completed the Iam handshake and its Connection has been registered. Subclasses decide what to do with the newly connected client here - for example calling Connection.actuate to register a message handler, or storing a reference to it.
Called when a registered client connection stops being addressable - see DisconnectReason. Runs on the single-threaded dispatch executor (mcups-dispatch), not the caller's thread, so it must return promptly.
Broadcasts bytes verbatim to every registered client's endpoint over the common socket - no encoding, no trim. Raw-bytes mirror of pushToAll(String). A payload above the OS datagram limit fails the Result (cause logged) rather than being sent.
Broadcasts a message to every registered client's endpoint over the common socket. "Registered" here means currently registered - a connection that has been terminate()d, or superseded by a same-name reconnect from a new origin, is pruned and no longer addressed.
Sends bytes reliably to every registered client's endpoint, opening (or reusing) each connection's reliable channel as needed. Unlike pushToAll, which short-circuits at the first failure, every peer is attempted even if an earlier one failed - a single peer's full in-flight window is routine and must not stop the broadcast from reaching everyone else; only the reported Result is the first failure.
Binds onClientMessage as the raw-bytes handler on every currently-registered connection: each receives an exact-length, undecoded, untrimmed copy of every application datagram (at most 65507 bytes - a larger inbound datagram is truncated, not rejected). Mutually exclusive with start per connection (last call wins). No socket is started - the one shared socket is already running.
Binds onClientMessage as the reliable-ordered handler on every currently-registered connection, opening (or reusing) each connection's reliable channel as needed. Unlike start / startBytes, every connection is attempted even if an earlier one failed - a single peer's full in-flight window is routine and must not stop the rest from being bound; only the reported Result short-circuits to the first failure.
Shuts the server down: terminates (fully deregisters) every registered Connection, leaving Registrations empty, then stops the common listener thread, releases the common socket, shuts the mcups-liveness executor (if one was started), shuts the mcups-keepalive, mcups-probe, and mcups-retransmit executors (if any were started), and shuts the dispatch executor.