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.Server(cfg)))
events.Dial("udp://host:9000", uio.WithLayers(ukcp.ClientLayer(opts), utls.Client(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 standalone server and dialer wrap the layers: NewServer's Serve listens on udp:// (or tcp://) addresses with Options.Handler receiving each connection's callbacks, and Dialer.Dial — DialContext, when the dial needs a bound; the package Dial uses DefaultDialer — returns the connection whose events reach Options.Handler the same way. There is no built-in TLS: KCP has no such standard, and what rides it is the wiring's to choose — put utls.Server or utls.Client above ServerLayer/ClientLayer in a WithLayers chain, exactly as over TCP. Both standalone endpoints need a Handler: reads arrive through its OnRead, as they do for any uio connection.
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' MaxBufferSize (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 MaxBufferSize at least the largest one in play.
Index ¶
Constants ¶
const DefaultSocketBuffer = 4 << 20
DefaultSocketBuffer is the kernel socket buffer the standalone endpoints size UDP sockets with when SocketReadBuffer or SocketWriteBuffer is zero: a window's burst, with room to spare.
Variables ¶
var DefaultDialer = &Dialer{}
DefaultDialer is the Dialer the package-level Dial uses. It runs with the default options, Handler among them, and lives until the process ends, like http.DefaultClient: set its Handler before dialing through Dial, and close it — which closes the connections it made — before the process goes.
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.
var ErrServerStarted = errors.New("ukcp: server already started")
ErrServerStarted reports a second Serve on a server that already serves.
Functions ¶
func ClientLayer ¶
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 ¶
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 Dialer ¶
type Dialer struct {
Options
// contains filtered or unexported fields
}
Dialer dials KCP sessions through one private UIO transport, which the first dial starts and Close stops: sessions share the Events — and with it the Handler their callbacks reach — and close with it. Dial bounds the dial by nothing, DialContext by its context. The dialed connection is one reliable stream, read through the Handler as any uio connection is; the connection returned is for writing, closing and addressing. For TLS over KCP, use the layer form — ClientLayer above utls.Client in a WithLayers chain — as with any other protocol.
The Events-level settings — Handler, MaxBufferSize, Pollers, Executor, SocketReadBuffer, SocketWriteBuffer, WriteBufferedThreshold, MaxOutboundBuffered, AllowHalfOpen — are read when the transport starts at the first dial and frozen with it; the session settings — MTU, the windows, KeepAlive and the rest — are read on every dial. Set them before dialing.
func NewDialer ¶
NewDialer returns a Dialer using opts, http.Server-style: the exported fields are the configuration, this constructor only fills them in.
func (*Dialer) Close ¶
Close stops the dialer's transport, and the sessions it made with it; dialing again reports net.ErrClosed. Closing again does nothing.
func (*Dialer) DialContext ¶
DialContext dials addr, in Serve's syntax — no scheme means udp — through the KCP layer, returning once the connection's stack opened; a client needs no handshake of its own, so this does not wait for the peer to answer, and the first segments retransmit until it does. ctx bounds the dial, not the connection after it. A dial after Close reports net.ErrClosed.
type Options ¶
type Options struct {
// Handler receives the connection callbacks of the standalone server and
// dialer. A layer hands its stream to the layer above instead; leaving
// Handler set there is ignored.
Handler uio.Handler
// 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'
// MaxBufferSize (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
// MaxBufferSize is the Events' MaxBufferSize, the socket read size. It
// must be at least MTU; zero leaves the Events default (4 KiB).
MaxBufferSize int
// WriteBufferedThreshold is the Events' WriteBufferedThreshold.
WriteBufferedThreshold int
// MaxOutboundBuffered is the Events' MaxOutboundBuffered.
MaxOutboundBuffered int
// AllowHalfOpen keeps a session open after its peer ended its stream.
AllowHalfOpen bool
// Pollers is the Events' event-loop count.
Pollers int
// ReusePort shares the bound address.
ReusePort bool
// Executor schedules the Events' connection turns.
Executor uio.Executor
// SocketReadBuffer and SocketWriteBuffer size the UDP socket's kernel
// buffers: a KCP session bursts a whole window — about 1.4 MiB at the
// defaults — and a kernel default of a few hundred KiB drops much of it.
// Zero takes DefaultSocketBuffer; a negative value leaves the socket's
// buffers as they came. A layer endpoint sizes its own sockets through
// uio.WithListenControl and uio.WithDialControl.
SocketReadBuffer int
SocketWriteBuffer int
}
Options configures ServerLayer and ClientLayer — and, through them, the standalone server and dialer — with the engine's parameters and the transport's. The zero value runs the Fast profile {false, 30ms, 2, 1}.
type Server ¶
type Server struct {
Options
// contains filtered or unexported fields
}
Server serves KCP over a UIO transport of its own. Configure the exported fields before Serve; Serve freezes the configuration. Every connection's callbacks reach the Handler it was configured with. There is no built-in TLS — KCP has no such standard; put a utls layer above ServerLayer in a WithLayers chain if one is wanted.
func NewServer ¶
NewServer returns a Server using opts, http.Server-style: the exported fields are the configuration, this constructor only fills them in.
func (*Server) Addrs ¶
Addrs returns the addresses the listeners bound — the ports the system chose, for addresses with port zero — once Serve has started. Before that it reports none.
func (*Server) Close ¶
Close stops the server: its listeners and its connections end, and a Serve running on it returns. Closing again does nothing.
func (*Server) Serve ¶
Serve listens on each address, in Serve's syntax, and serves until Close: it blocks, and reports why the transport stopped. An address without a scheme listens for UDP, the network KCP runs on commonly. A listener's chain is KCP, so every connection the Handler hears is one reliable stream. A listen that fails stops the ones made before it and returns its cause.
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)