ukcp

package
v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference License

ukcp is KCP for Go, built on the uio event engine: a reliable, ordered byte stream over an unreliable datagram transport. Every session runs in the connection's own turns on a shared worker pool — no goroutine and no timer of its own; its clock is the connection's turn timer. The protocol engine is the battle-tested one from xtaci/kcp-go, vendored file-for-file (see License).

Highlights

  • A stream over anything. As a uio.PacketLayer it reads a packet connection's datagrams — UDP, IP, unixgram — one per turn, and hands the layers above a reliable stream. Above a stream connection it frames its own segments, so it composes in either direction with TLS and with itself.
  • Zero goroutines, zero timers. The flush clock, retransmissions, window probes and the keepalive all run on the session's own turn timer — no goroutine of its own, no timer of its own. An idle session wakes only for the keepalive; turn KeepAlive off to stop even that.
  • TLS, composed not bundled. There is no built-in TLS: KCP has no wss:// of its own to match, so TLS is a layer above (or below) by your choice, through uio.WithLayers.
  • A real EOF. CloseWrite queues an empty push behind the data: an ended stream reaches the peer in order and reliably, so io.EOF travels the stack and half-close works through TLS too.
  • Portable segments. The wire is the KCP every implementation speaks (24-byte header, little-endian, PUSH/ACK/WASK/WINS); bulk send and receive batch into one sendmmsg/recvmmsg on Linux and answer a small read turn's output together, so the system-call side stays out of the way.
  • Bounded by design. The windows, the buffered bytes, the MTU and the first segment's wait are all bounded and configurable, and a session reports itself — RTT, congestion, queue depth — through uio.FindLayer.

Install

import "github.com/urpc/uio/ukcp"

The package ships inside the uio module; go get github.com/urpc/uio fetches it.

Quick start

KCP has no handshake and no connection of its own, so the server and the client take a uio.Handler, as every uio connection does: reads arrive in its callbacks, writes go through the connection a dial returns.

package main

import (
	"log"

	"github.com/urpc/uio"
	"github.com/urpc/uio/ukcp"
)

func main() {
	server := ukcp.NewServer(ukcp.Options{Handler: uio.FuncHandler{
		Read: func(c uio.Conn) error { _, err := c.WriteTo(c); return err },
	}})
	log.Fatal(server.Serve("udp://:9000"))
}

The client half, in the same shape:

dialer := ukcp.NewDialer(ukcp.Options{Handler: uio.FuncHandler{
	Read: func(c uio.Conn) error {
		n := c.InboundBuffered()
		if n == 0 {
			return nil
		}
		buf := make([]byte, n)
		log.Printf("from the peer: %q", c.Peek(buf))
		_, err := c.Discard(n)
		return err
	},
}})

conn, err := dialer.Dial("udp://example.org:9000") // or DialContext, with a bound
if err != nil {
	log.Fatal(err)
}
defer conn.Close()

_, _ = conn.Write([]byte("hello"))

Serve takes any number of addresses — udp://, tcp://, a bare host:port means UDP — and blocks until Close; Dial bounds nothing and DialContext bounds the dial by its context, as uio's own pair does. A dial returns once the session exists; its stream reaches you through Handler's OnRead, and the returned uio.Conn is for writing, closing, deadlines and addressing. A client needs no acknowledgement to open: the first segments retransmit until the peer answers.

How it works

  1. A session per peer. On a UDP listener, every source address is one session; ServerLayer waits for the peer's first valid segment to name the conversation, and ClientLayer picks a random one at once. Every segment is acknowledged as it arrives; one that never does is retransmitted.
  2. Segments in, a stream out. Input is decoded in the connection's turn — a datagram per turn on a packet connection, self-framed segments on a stream one — and the in-order bytes go up the stack as they become whole.
  3. A clock that is the turn's timer. One timer per session, armed for the engine's next due: a flush, a retransmission, a window probe, the keepalive. Writes and read turns flush at once; the interval only paces background work.
  4. The end travels in order. CloseWrite queues an empty push behind the data; the peer's engine delivers it after every byte before it, and the layer above reads io.EOF. A stream connection below that ends is EOF at a segment boundary and io.ErrUnexpectedEOF inside one.

Configuration

Options holds every setting; Server, Dialer and the layers embed the same type, the zero value is the defaults — KCP's Fast profile — and Options.Validate reports up front what a session would refuse.

Field Default What it does
MTU 1400 Largest segment, header included (24..1500). Must not exceed the Events' MaxBufferSize — on both ends, since the peer's segments arrive into this end's read buffer.
SendWindow / RecvWindow 1024 Windows in segments, each at most 65535 — the header's window field is a uint16. A window times the MTU bounds what a session holds, about 1.4 MiB each way.
NoDelay off The engine's low-latency RTO mode: a 30 ms floor instead of 100 ms.
Interval 30 ms The engine's flush cadence, 10 ms to 5 s. Data never waits for it.
Resend 2 Fast-retransmit threshold; a negative value turns fast retransmit off.
CongestionControl off Enables the engine's congestion window. Every KCP profile runs it off; flow control is the windows' and the timer's.
DeadLink 20 Retransmissions of one segment before the session ends with ErrDeadLink.
HandshakeTimeout 10 s How long a server waits for the peer's first segment. KCP has no handshake, but a peer that never speaks must not hold a connection for ever: it ends with ErrPeerSilent. A negative value waits without a bound; a client never waits.
KeepAlive 10 s An idle session probes the peer's window this often; silence for three periods ends it with ErrKeepAliveTimeout. A negative value disables keepalive.
MaxBuffered 4 MiB Bytes a session holds for the writer; a write past it returns ErrOutboundOverflow.
Handler none The connection callbacks. Required by Server and Dialer; a layer hands its stream to the layer above instead.
MaxBufferSize Events default The Events' socket read size; must be at least MTU.
WriteBufferedThreshold off Passed to the Events: writes below it join the turn's batch.
MaxOutboundBuffered off Passed to the Events: a hard limit on the socket's queue, returning ErrOutboundOverflow.
AllowHalfOpen off Keeps a session open after the peer ends its stream, as a TCP connection would be.
Pollers Events default Event loops.
ReusePort off Sets SO_REUSEPORT on listeners.
Executor uio default Runs connection turns on the native backend.
SocketReadBuffer / SocketWriteBuffer 4 MiB Kernel socket buffers the standalone endpoints size their UDP sockets with. A session bursts a whole window and the kernel default — a few hundred KiB — drops much of it; a negative value leaves the socket alone. A layer endpoint sizes its own sockets with uio.WithListenControl and uio.WithDialControl.

Invalid combinations — an MTU past the engine's buffers, a window past 65535, an interval outside 10 ms..5 s — make Serve and Dial return ErrInvalidOptions.

Backpressure. A slow reader closes the receive window, the sender's queue fills, and Write returns ErrOutboundOverflow rather than blocking; when the reader catches up the queued data leaves by itself. MaxBuffered and the send window bound what a session holds, MaxOutboundBuffered bounds the socket's queue, and a peer that stops acknowledging is found out by the dead-link bound.

As a protocol layer

ServerLayer and ClientLayer return a uio.Layer — and a uio.PacketLayer, the marker a chain on a packet connection must start with, or the endpoint refuses it with uio.ErrLayersNeedStream — for stacks of your own:

// udp -> kcp -> tls: a TLS stream carried by KCP over UDP
listener, err := events.Listen("udp://:9000", uio.WithLayers(
	ukcp.ServerLayer(ukcp.Options{}), utls.Server(tlsConfig),
))
conn, err := client.DialContext(ctx, "udp://example.org:9000", uio.WithLayers(
	ukcp.ClientLayer(ukcp.Options{}), utls.Client(tlsConfig),
))

The same layers run above a stream — the segments frame themselves on the connection's own length field — so tcp -> kcp, tcp -> tls -> kcp and KCP above KCP all compose:

// tcp -> kcp -> tls, and kcp -> kcp over UDP
uio.WithLayers(ukcp.ServerLayer(opts), utls.Server(tlsConfig))
uio.WithLayers(ukcp.ServerLayer(opts), ukcp.ServerLayer(opts))

The layer hands the layer above one byte stream, opens it when the peer's first segment names the conversation, and ends it on the peer's end of stream. A stream connection below that ends travels up as io.EOF at a segment boundary and io.ErrUnexpectedEOF inside one. The stream dialect frames with frg=0; a segment in message mode — which the dialect never sends — ends the session with ErrProtocol, because its sequence number could never be delivered in order. A datagram the Events' MaxBufferSize cannot hold would be truncated below the layer, so a session whose MTU exceeds it is refused with ErrInvalidOptions instead.

There is deliberately no TLSConfig option. KCP has no standard TLS port or URL scheme as wss does, so the composition is yours: put utls.Server or utls.Client above ServerLayer/ClientLayer in the WithLayers chain and configure TLS there, exactly as over TCP. The standalone Server/Dialer are bare KCP; for TLS use the layer form above.

A layered UDP listener refuses DialPeer with uio.ErrUnsupported: the peer's connection belongs to the stack, which only the stack opens, and a socket-level connection would bypass every layer.

Session state

The session a connection carries reports itself through uio.FindLayer:

state, ok := uio.FindLayer[interface{ State() ukcp.SessionState }](conn)
if ok {
	s := state.State()
	log.Printf("rtt %v, cwnd %d, queued %d, inflight %d", s.SRTT, s.CWnd, s.Queued, s.Inflight)
}

State may be read from any goroutine, including from an OnBytesWritten observer inside a write; the snapshot is published, never taken under the engine's lock.

Rules of the road

  • Reads are the Handler's. As with every uio connection, inbound bytes arrive in OnRead (PeekChunk/Discard); the Conn a dial returns is for writing, closing and addressing. Handler is required — Serve and Dial refuse a missing one.
  • Accepted is not delivered. A nil error from Write means the session took the bytes — the writes below flushed at once — not that the peer has them; KCP retransmits until it does. ErrOutboundOverflow means the session's buffer is full: retry once the queue drains, or close.
  • The server cannot speak first. KCP has no handshake, so a session begins with the client's first segment. A pure download must send a byte first; a peer that never does is reclaimed when HandshakeTimeout passes, a connection the Handler never heard of.
  • Half-close. CloseWrite ends this direction reliably and the session goes on receiving; the peer reads io.EOF once the bytes before it arrived. With the Events' AllowHalfOpen set, a peer's own end leaves this direction writable just the same; without it the framework closes the connection when the peer's stream ends. A graceful Close sends the end best effort — the connection closes below it.
  • Closing. Server.Close and Dialer.Close request shutdown and return at once; sessions the dialer made close with it, and a dial after Close reports net.ErrClosed. A server serves once.
  • Windows and MTU are bounded. Windows at most 65535 segments, MTU at most 1500 bytes and at most the Events' read buffer; Options.Validate reports what a session would refuse.

The API reference documents every type and method.

License

Apache License 2.0.

The protocol engine under internal/kcp is xtaci/kcp-go v5.7.1, MIT licensed (internal/kcp/LICENSE), vendored with three patches marked ukcp: in kcp.go — a stream-mode empty send as the end-of-stream marker, a test clock hook, and a flush type that keeps an answer-only flush from moving the send queue — described in internal/kcp/README.md.

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

View Source
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

View Source
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.

View Source
var ErrDeadLink = errors.New("ukcp: link dead")

ErrDeadLink reports a session whose peer stopped acknowledging: a segment was retransmitted the DeadLink bound times.

View Source
var ErrInvalidOptions = errors.New("ukcp: invalid options")

ErrInvalidOptions reports options no session can run with; every connection through such a layer ends with it.

View Source
var ErrKeepAliveTimeout = errors.New("ukcp: keepalive timeout")

ErrKeepAliveTimeout reports a session whose peer sent nothing back for three keepalive periods.

View Source
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.

View Source
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.

View Source
var ErrServerStarted = errors.New("ukcp: server already started")

ErrServerStarted reports a second Serve on a server that already serves.

Functions

func ClientLayer

func ClientLayer(opts Options) 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 Dial

func Dial(addr string) (uio.Conn, error)

Dial connects through DefaultDialer with no deadline; see Dialer.Dial.

func ServerLayer

func ServerLayer(opts Options) 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 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

func NewDialer(opts Options) *Dialer

NewDialer returns a Dialer using opts, http.Server-style: the exported fields are the configuration, this constructor only fills them in.

func (*Dialer) Close

func (d *Dialer) Close() error

Close stops the dialer's transport, and the sessions it made with it; dialing again reports net.ErrClosed. Closing again does nothing.

func (*Dialer) Dial

func (d *Dialer) Dial(addr string) (uio.Conn, error)

Dial is DialContext with no deadline, as a server's Serve takes none.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, addr string) (uio.Conn, error)

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}.

func (Options) Validate

func (o Options) Validate() error

Validate reports what a layer built from o would refuse.

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

func NewServer(opts Options) *Server

NewServer returns a Server using opts, http.Server-style: the exported fields are the configuration, this constructor only fills them in.

func (*Server) Addrs

func (s *Server) Addrs() []net.Addr

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

func (s *Server) Close() error

Close stops the server: its listeners and its connections end, and a Serve running on it returns. Closing again does nothing.

func (*Server) Serve

func (s *Server) Serve(addrs ...string) error

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)

Directories

Path Synopsis
internal
kcp
if build tag debug is not set, debugLog is a no-op eliminated at compile time
if build tag debug is not set, debugLog is a no-op eliminated at compile time

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL