Documentation
¶
Overview ¶
Package ukcp runs KCP — a reliable, ordered byte stream over an unreliable datagram transport — as a UIO layer, with the protocol engine vendored from github.com/xtaci/kcp-go (see internal/kcp).
ServerLayer and ClientLayer return a uio.Layer, so KCP composes with any other layer: it takes a packet connection's datagrams (it is a uio.PacketLayer) or a stream connection's bytes, and hands the layers above one reliable stream — TLS and the like can run over it:
events.Listen("udp://:9000", uio.WithLayers(
ukcp.ServerLayer(opts), utls.ServerLayer(utls.LayerOptions{TLSConfig: cfg})))
events.Dial("udp://host:9000", uio.WithLayers(
ukcp.ClientLayer(opts), utls.ClientLayer(utls.LayerOptions{TLSConfig: cfg})))
Nothing costs a goroutine: every session runs on the connection's turns, its clock is the layer's timer, and an idle session wakes for nothing.
A KCP layer above another one is a stream above a stream: the segment framing carries it, so nesting composes like any other stream layer. A stream connection below a KCP layer is framed by the engine's headers: one that ends at a segment boundary ends this stream too, and one that ends inside a segment aborts it with io.ErrUnexpectedEOF. The stream dialect sends frg=0 only; a segment in message mode ends the session with ErrProtocol, since its sequence number could never be delivered in order.
A session's stream ends in order: CloseWrite queues an empty push after the data written before it, a marker the peer reads back as the end of the stream (io.EOF at the Handler, or the end of the layer above). A graceful whole-connection close sends the same marker best-effort — the connection closes below it, so its retransmissions end there; for a reliable end, end the writing half with CloseWrite first. A peer that goes silent is found out by KeepAlive (WASK probes) and by the engine's dead-link bound.
MTU must not exceed the Events' ReadBufferSize (4 KiB by default), or the socket truncates datagrams and segments never reassemble; the defaults (1400) fit. Both ends' MTU matter: a segment arrives into this end's read buffer, so a peer's larger MTU must fit here too — run both ends with the same MTU, or keep ReadBufferSize at least the largest one in play.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrDeadLink = errors.New("ukcp: link dead")
ErrDeadLink reports a session whose peer stopped acknowledging: a segment was retransmitted the DeadLink bound times.
var ErrInvalidOptions = errors.New("ukcp: invalid options")
ErrInvalidOptions reports options no session can run with; every connection through such a layer ends with it.
var ErrKeepAliveTimeout = errors.New("ukcp: keepalive timeout")
ErrKeepAliveTimeout reports a session whose peer sent nothing back for three keepalive periods.
var ErrPeerSilent = errors.New("ukcp: no KCP segment arrived from the peer")
ErrPeerSilent reports a server-side connection that heard no valid KCP segment within HandshakeTimeout: KCP has no handshake, but a peer that never speaks must not hold the connection for ever.
var ErrProtocol = errors.New("ukcp: protocol violation")
ErrProtocol reports a peer speaking outside the stream dialect this layer runs — a segment in KCP's message mode, whose sequence number could never be delivered in order. The session ends with it.
Functions ¶
func ClientLayer ¶
func ClientLayer(opts LayerOptions) uio.Layer
ClientLayer runs the client side of KCP as a uio.Layer: it opens the layers above at once with a conversation id of its own, and the dial does not wait for the peer — the first segments retransmit until it answers. One layer dials one peer.
func ServerLayer ¶
func ServerLayer(opts LayerOptions) uio.Layer
ServerLayer runs the server side of KCP as a uio.Layer, for a chain of your own — over a packet connection (UDP and the like, where it reads a datagram per turn) or over a stream one (TCP, TLS), which its segments self-frame on. It opens the layers above when the peer's first segment names the session's conversation id, and hands them one reliable stream.
Types ¶
type LayerOptions ¶ added in v1.9.0
type LayerOptions = Options
LayerOptions names the options a ServerLayer or ClientLayer runs with: the protocol's own Options, under the name every layer package's options share.
type Options ¶
type Options struct {
// MTU is the largest segment, header included. The engine's buffers hold
// 1500, so 24..1500; the default is 1400. It must not exceed the Events'
// ReadBufferSize (4 KiB by default) — on both ends: a segment from the
// peer must fit this end's read buffer too.
MTU int
// SendWindow and RecvWindow are the windows, in segments: how much a
// session may have in flight and how much it buffers for the reader.
// Zero takes the default of 1024. A window times the MTU bounds what a
// session holds — 1024 segments at 1400 is about 1.4 MiB each way.
SendWindow int
RecvWindow int
// NoDelay runs the engine's low-latency RTO mode (30ms floor instead of
// 100ms). The default, part of the Fast profile, is false.
NoDelay bool
// Interval is the flush cadence: the engine's clock for retransmissions
// and window probes. Data never waits for it — a write and every read
// flush at once — so it only paces the engine's background work. The
// engine clamps it to 10ms..5s; zero takes the Fast profile's 30ms.
Interval time.Duration
// Resend is the fast-retransmit threshold: how many later segments must
// be acknowledged before a segment is resent without waiting for its
// timeout. Zero takes the Fast profile's 2; a negative value disables
// fast retransmit.
Resend int
// CongestionControl enables the engine's congestion window (kcp-go's
// nocwnd=0). It is off by default, as every KCP profile runs it: flow
// control is the windows' and the retransmission timer's. The engine
// starts a congestion window at zero and opens it one segment per
// acknowledgement, so enabling it costs throughput on a healthy link and
// buys gentler retransmission on a badly congested one.
CongestionControl bool
// DeadLink is how many retransmissions of one segment mark the link dead;
// the session then ends with ErrDeadLink. Zero takes the default of 20.
DeadLink int
// HandshakeTimeout bounds a server's wait for the peer's first segment.
// KCP has no handshake, but a peer that never speaks must not hold a
// connection for ever. Zero takes the default of 10s; a negative value
// waits without a bound. A client never waits: its stack opens at once.
HandshakeTimeout time.Duration
// KeepAlive is how long a session may hear nothing from its peer before
// sending a window-probe (WASK) ping; a peer silent for three periods
// ends the session with ErrKeepAliveTimeout. Zero takes the default of
// 10s; a negative value disables keepalive.
KeepAlive time.Duration
// MaxBuffered bounds the bytes a session has taken from its writer and
// not yet handed to the socket; a write that would pass it returns
// ErrOutboundOverflow. Zero takes the default of 4 MiB.
MaxBuffered int
}
Options configures ServerLayer and ClientLayer with the engine's parameters. The zero value runs the Fast profile {false, 30ms, 2, 1}.
type SessionState ¶
type SessionState struct {
Conv uint32 // the conversation id the session runs with
SRTT time.Duration // the smoothed round-trip time
RTO time.Duration // the retransmission timeout in force
CWnd uint32 // the congestion window, in segments
RemoteWnd uint32 // the window the peer last advertised, in segments
Queued int // segments taken from the writer, not yet sent
Inflight int // segments sent, not yet acknowledged
}
SessionState reports where one session stands; a connection's layer state is read through uio.FindLayer:
state, ok := uio.FindLayer[interface{ State() ukcp.SessionState }](conn)