MultiConnectionUDPClient
The client-side counterpart to MultiConnectionUDPServer: opens the Iam handshake, then owns the entire subsequent session, over one socket.
The "one socket for everything" invariant
MultiConnectionUDPServer replies to a client's Iam datagram, and addresses every later datagram, straight back to the source address and port the Iam arrived from - because that is the 5-tuple whose NAT mapping is actually open (issue #1's NAT fix). This class binds exactly one DatagramSocket in its constructor and uses it for the handshake send, the handshake reply, and every later send and receive, so that invariant cannot accidentally be violated by opening a second socket to listen for the reply.
Do not build this on UDPSendReceiveServer - that type is a two-socket primitive (sendSocket plus a separately-bound listenSocket); reusing it here would silently reintroduce the exact bug issue #1 fixed, since the handshake reply would arrive on a different local port than the one this client's NAT mapping was opened from.
Concurrency
Mirrors MultiConnectionUDPServer's own listener-thread + dispatch-executor split: one background daemon listener thread only demultiplexes - receive() -> switch on the DatagramType tag (byte 0) -> drop a keepalive/probe or strip the 0x90 frame and hand the payload to the dispatch executor. The dispatch executor is a single daemon thread (mcupc-dispatch) that invokes the caller's onMessage callback passed to start, so a slow callback cannot stall the socket read loop.
handshake itself remains a blocking one-shot call, mirroring the server's own handshake state machine running synchronously rather than through a dispatch executor - only steady-state message delivery, after start, is asynchronous.
A third daemon thread (mcupc-keepalive, a ScheduledExecutorService) exists only once startKeepAlive has been called; it sends 0x80 keepalive datagrams on an idle-aware cadence and is shut by stop. See the scheduled-keepalive sequence diagram in docs/plans/12-scheduled-keepalive/plan.md §2.8.
A fourth daemon thread (mcupc-probe, also a ScheduledExecutorService) exists only once startProbe has been called; it sends 0x81 probe datagrams (an 8-byte big-endian sequence) on a fixed cadence for the link-quality probe and is shut by stop. See docs/plans/13-link-quality-probe/plan.md §2.9.
A fifth daemon thread (mcupc-retransmit, also a ScheduledExecutorService) exists only once a reliable channel is opened - either a channel(RELIABLE_ORDERED).send/actuate* call or an inbound 0xA0/0xA1; it retransmits unacked 0xA0 frames and emits standalone 0xA1 acks, runs no application code, and is shut by stop.
Boundary-Ring notes (mirrors CommonChannel's):
One UDP socket carries the handshake and the entire session.
The JDK permits a concurrent DatagramSocket.send while a DatagramSocket.receive is in progress.
socket is received on only by the listener thread, but sent on from any thread (send, sendKeepAlive, the
mcupc-keepalivetick, themcupc-probetick, themcupc-retransmittick); the listener thread itself never sends application data - it answers an inbound0x81probe with an0x82reply inline.
Construction side effects
Instantiating this class binds an ephemeral OS UDP port immediately - a documented construction side effect, the same convention CommonChannel uses.
Ordering contract (not enforced in code)
Call handshake once, then start (or startBytes, or a channel actuate*) once. Calling handshake itself before a successful prior call, or twice, is undefined behaviour - matching the level of guarding MultiConnectionUDPServer itself applies to its own lifecycle. The listener start itself, however, is now idempotent: start, startBytes, and channel(UNRELIABLE).actuate* may each be called any number of times, in any order, after handshake - the last one to bind wins, and only the first one to run actually starts the listener thread. A handshake that fails - including a refusal surfaced as a HandshakeRefusedException - leaves the client safe to stop and discard.
This class does not implement AutoCloseable, matching MultiConnectionUDPServer: lifecycle is start/stop, not use { }.
Concurrent-call contract
stop is idempotent: calling it more than once, from any thread, is safe and every call returns Result.success (the underlying socket-close and executor-shutdown are themselves idempotent/non-throwing). stop may also be called concurrently with a blocked handshake or a running start listener - closing socket is what unblocks a listener parked in receive(). A send racing a concurrent stop does not throw: it either completes normally or observes the now-closed socket and returns Result.failure. start and handshake themselves are not safe to race against each other or against a second concurrent call to either - see the "Ordering contract" below. startKeepAlive / stopKeepAlive are safe from any thread and may race stop: a startKeepAlive after stop fails its Result; an in-flight keepalive tick either sends or observes the closed socket and fails its own Result. startProbe / stopProbe carry the same contract: safe from any thread, and a startProbe after stop fails its Result.
See the sequence diagram in docs/plans/3-public-client-handshake/plan.md §2.2 for the canonical handshake/listener/dispatch flow.
Binary application payloads
Application data may be raw bytes: send takes a ByteArray and startBytes arms the listener with a raw-bytes handler that receives an exact-length, undecoded, untrimmed copy of every datagram's payload. The session is framed (webtools-udp 2.x): send wraps the payload in an 0x90 unreliable datagram and the listener strips the frame before delivery, so any payload bytes ride intact - there is no reserved first byte and the pre-2.0 "lead with 0x00 / >= 0x80" rule is gone. Control datagrams (0x80 keepalive, 0x81/0x82 probe) are classified out by their DatagramType tag and never delivered. An inbound datagram over 65507 bytes is delivered truncated, not rejected; on send, a payload over the OS datagram limit fails the Result. Keep frames under the path MTU (~1200 bytes) for real-network use.
Reliable-ordered channel
channel(DeliveryMode.RELIABLE_ORDERED) sends acked, retransmitted, in-order 0xA0/0xA1 traffic to the server - 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. The channel's engine is created lazily, on the first reliable send or the first inbound 0xA0/0xA1 on channel 0x00 from the server, whichever comes first - obtaining the handle or binding its handler alone creates nothing, and a frame on any other channel is dropped without creating one; a send after stop fails with IllegalStateException.
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.
Parameters
the server's address to hand shake with and send to
the server's common listen port; defaults to MultiConnectionUDPServer.COMMON_LISTEN_PORT
size of the datagram receive buffer, 512..65507; defaults to 65507 so no well-formed datagram is truncated. A datagram larger than this is delivered truncated, not rejected (a WARN is logged).
the scheduled-keepalive timer seam backing startKeepAlive / stopKeepAlive; the public constructor supplies a real PeriodicScheduler (mcupc-keepalive), tests inject a fake. Mirrors HandshakeCoordinator's injected keepAliveSchedule.
the link-quality probe timer seam backing startProbe / stopProbe; the public constructor supplies a real PeriodicScheduler (mcupc-probe), tests inject a fake.
the timer seam backing the reliable-channel retransmit tick; the public constructor supplies a real PeriodicScheduler (mcupc-retransmit), tests inject a fake.
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)
Throws
if an ephemeral local port could not be bound
if receiveBufferBytes is outside 512..65507, or if reliableMaxMessageBytes is outside 1..8192
Constructors
The public client constructor - unchanged three-parameter surface plus the new reliableMaxMessageBytes knob. Delegates to the internal seam constructor with real PeriodicScheduler instances (mcupc-keepalive, mcupc-probe, mcupc-retransmit), whose executors/threads stay lazy until the first startKeepAlive / startProbe / reliable channel use.
Properties
Functions
The delivery-mode-scoped handle for this client's session with the server. Each DeliveryMode has its own sequence space and its own inbound handler - binding one never disturbs the other. Unlike the Connection side, both modes are always fully supported here (there is no UnsupportedOperationException case): the client always talks to exactly one server.
The latest link-quality snapshot, or null until the first PONG has come back.
Sends bytes to the server as the payload of one 0x90 unreliable application datagram ([0x90][channel][bytes]) over the shared socket. Safe to call from any thread. send(String) is a UTF-8 wrapper over the same private sendUnreliable this delegates to.
Sends message to the server over the shared socket. Safe to call from any thread, including while receiveLoop is blocked in a receive on another.
Sends one minimal 0x80 keepalive datagram, one-shot (mirrors Connection.keepAlive). For a library-managed cadence use startKeepAlive.
Starts the background listener thread (if not already running): receives datagrams on socket until stop is called, drops 0x80 keepalive and 0x81/0x82 probe datagrams silently, and dispatches every 0x90 frame's stripped payload (decoded to text) to onMessage on the single-threaded dispatch executor (never on the listener thread itself), so a slow onMessage cannot stall the read loop.
Raw-bytes counterpart to start: dispatches an exact-length, undecoded, untrimmed copy of every non-keepalive datagram to onMessage. Mutually exclusive with start - last call wins - and idempotent in the same way: calling this (or start, or channel(UNRELIABLE).actuate*) again rebinds the unreliable handler rather than starting a second listener thread. Call after handshake.
Starts an opt-in, idle-aware background keepalive: every ~intervalMillis of output silence this client sends one 0x80 keepalive on the shared socket to hold its NAT mapping open, until stopKeepAlive or stop. Application sends reset the idle timer, so a busy client sends no redundant keepalives.
Starts an opt-in link-quality probe: every intervalMillis this client sends one 0x81 probe (an 8-byte big-endian sequence) to the server, and each matching 0x82 reply updates a smoothed RTT / jitter / packet-loss estimate readable via linkQuality. Off until called; runs until stopProbe or stop. Backed by one daemon thread (mcupc-probe) created on the first call. Calling this again re-arms it (last call wins). Call after handshake
Stops the listener thread, shuts the keepalive scheduler (if startKeepAlive armed one), shuts the probe scheduler (if startProbe armed one), shuts the retransmit scheduler and closes the reliable engine (if a reliable channel was ever opened), closes the socket, and shuts the dispatch executor. A reliable send after this returns fails with IllegalStateException rather than buffering into a closed socket (design §7.7). Every step runs even if an earlier one failed, so a partial failure never leaks the bound port. Once called, this instance should be discarded.
Stops the background keepalive started by startKeepAlive. Idempotent and safe to call even if startKeepAlive was never called. stop also does this.
Stops the probe started by startProbe. Idempotent; stop also does this. The last linkQuality snapshot remains readable. A probe still unanswered when the probe stopped is counted as lost once it passes the loss horizon, so packetLossRatio can still settle for up to three probe intervals after this call.