kcp

package module
v5.7.11 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 40 Imported by: 259 modules, 321 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

kcp-go

GoDoc Created At MIT licensed Coverage Status

Table of Contents

Introduction

kcp-go is a Reliable-UDP library for golang.

This library provides a reliable, ordered byte-stream transport over UDP. Optional FEC and packet encryption are available. Encryption can hide packet contents, but random per-packet nonces do not make network traffic anonymous: endpoints, packet sizes, timing, and traffic volume may still be observable. It has been deployed across a range of devices and applications, including online games, live broadcasting, file synchronization, and network acceleration.

Latest Release

Quick Start

kcp-go implements net.Conn and net.Listener, so applications can use familiar stream I/O. These standalone examples show a basic echo server and client; they use no packet encryption or FEC.

Echo server:

package main

import (
	"io"
	"log"
	"net"

	"github.com/xtaci/kcp-go/v5"
)

func main() {
	ln, err := kcp.Listen("127.0.0.1:12345")
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go func(conn net.Conn) {
			defer conn.Close()
			if _, err := io.Copy(conn, conn); err != nil {
				log.Println(err)
			}
		}(conn)
	}
}

Echo client:

package main

import (
	"fmt"
	"io"
	"log"

	"github.com/xtaci/kcp-go/v5"
)

func main() {
	conn, err := kcp.Dial("127.0.0.1:12345")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	payload := []byte("hello over KCP")
	if _, err := conn.Write(payload); err != nil {
		log.Fatal(err)
	}
	reply := make([]byte, len(payload))
	if _, err := io.ReadFull(conn, reply); err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(reply))
}

For optional packet encryption or FEC, use ListenWithOptions and DialWithOptions. Both peers must use matching encryption keys. The sender's FEC shard settings configure its encoder; the receiver can automatically detect and adapt to the sender's data/parity shard counts. See Godoc for configuration details.

Features

  • Reliable, ordered byte-stream delivery over UDP with configurable latency/throughput trade-offs.
  • net.Conn and net.Listener APIs; the familiar interface does not make the transport TCP.
  • Optional Reed-Solomon FEC to recover some packet loss, with configurable data/parity shard counts.
  • The FEC receiver can automatically detect and adapt to the sender's shard counts.
  • Optional packet encryption, including AEAD for packet-level integrity and authentication.
  • SNMP statistics are enabled by default. To disable statistics collection, build with go build -tags kcp_no_snmp ./...; in this build, Snmp is an empty placeholder and its statistics fields and reporting methods are unavailable.
  • A shared timer scheduler and batched, platform-specific UDP I/O to support many sessions efficiently.
  • On Linux, macOS, Windows, FreeBSD, OpenBSD, NetBSD, and DragonFly, wildcard UDP listeners use OS control messages to track each packet's local destination and send replies from that address. Other platforms use generic UDP handling without guaranteed source-address preservation.
  • Designed for high concurrency; capacity depends on workload, configuration, and hardware.
  • Based on skywind3000's KCP, with additional features and optimizations.

Documentation

For complete documentation, see the associated Godoc.

Layer-Model of KCP-GO

layer-model

Design and Tuning Notes

1. Slice vs. Container/List

The KCP flush path scans the in-flight send buffer to find segments that need transmission or retransmission. The ring-buffer representation supports sequential traversal with good locality; the scan cost depends on the number of in-flight segments and how often the session is updated.

I wrote a benchmark comparing sequential loops through a slice and a container/list here:

BenchmarkLoopSlice-4   	2000000000	         0.39 ns/op
BenchmarkLoopList-4    	100000000	        54.6 ns/op

The list structure introduces heavy cache misses compared to the slice, which offers better locality. In the linked benchmark, for 5,000 connections with a 32-window size and a 20 ms update interval, using a slice costs 6 μs (0.03% CPU) per kcp.flush(), whereas using a list costs 8.7 ms (43.5% CPU). These figures are benchmark-specific; actual cost depends on workload and hardware.

2. Timing Accuracy and RTT Estimation

Timing is critical for the RTT estimator. Inaccurate timing can cause premature or delayed retransmissions. KCP uses currentMs(), which derives elapsed monotonic time from a package reference point. The time.Now() numbers below are measurements from a historical benchmark on the listed hardware, not portable performance guarantees.

The benchmark for time.Now() is here:

BenchmarkNow-4         	100000000	        15.6 ns/op

The number of clock reads varies with the flush path: KCP samples time while checking retransmission deadlines and when preparing transmissions. The time.Now() benchmark above is historical and should not be treated as a measurement of current currentMs() cost or as a per-flush cost estimate.

3. Memory Management

Many packet buffers are obtained from the package-wide defaultBufferPool, which provides buffers with a fixed capacity of 1500 bytes (mtuLimit). Buffers are returned to the pool when they are no longer needed, reducing repeated allocations. The pool uses sync.Pool, so the Go runtime may discard pooled buffers during garbage collection; reuse and retention are not guaranteed.

4. Per-session Application Write Rate Limiting

UDPSession.SetRateLimit(bytesPerSecond) configures an independent token-bucket rate limit for application data submitted through Write and WriteBuffers. The limit is measured in application bytes per second. It does not count KCP/FEC/encryption overhead, FEC parity, retransmissions, SendOOB traffic, or UDP/IP headers. Rate limiting is disabled by default, and passing 0 disables it. A throttled write waits for tokens while remaining interruptible by its write deadline, socket write errors, and session closure.

The bucket allows an initial burst of up to maxBatchSize * maxPacketSize bytes (currently 64 × 1472 = 94,208 bytes), then limits the average rate at which writes are accepted. Writes larger than the burst capacity are admitted in rate-limited chunks. This controls application write throughput rather than the exact rate of UDP packets on the wire.

sess.SetRateLimit(256 * 1024) // limit this session to 256 KiB/s
sess.SetRateLimit(0)           // disable rate limiting

5. Information Security

Applications commonly use TLS or a similar protocol to protect application data. That protection does not extend to the KCP and FEC headers added below the application layer. kcp-go's packet protection is a separate layer: it can encrypt and, when using AEAD, authenticate each UDP payload, including those transport headers.

Packet integrity depends on the selected mode. When a non-AEAD BlockCrypt is configured, kcp-go adds a CRC-32 checksum; if an encryption cipher is enabled, the checksum is carried within the encrypted packet. After CFB decryption, the receiver verifies this checksum and drops packets corrupted by accidental bit errors. This is only an anti-corruption check, not cryptographic anti-tamper protection: CRC-32 is unkeyed, and its linearity combined with the malleability of modes such as CFB means an active attacker may be able to modify packets without detection. Do not rely on non-AEAD modes for cryptographic integrity or authentication. AEAD modes authenticate each packet's encrypted contents and are recommended when protection against deliberate packet modification is required. AEAD packet authentication proves possession of the configured key; it does not by itself establish a peer's identity, replace secure key management, or guarantee application-level replay protection.

Packet encryption protects packet contents, including FEC and KCP headers, but does not hide traffic metadata such as endpoints, packet sizes, timing, or traffic volume. A random nonce for each packet helps prevent repeated encryption inputs from producing repeated ciphertext, but it does not conceal this metadata or provide anonymity. Without packet encryption, packet contents are transmitted in plaintext. Algorithm performance varies by hardware and workload, so benchmark the available options in your deployment rather than assuming one cipher is always faster.

Other possible attacks on kcp-go include:

  • Traffic analysis: Packet sizes, timing, and endpoints can reveal communication patterns even when packet contents are encrypted. Multiplexing streams with smux does not eliminate traffic analysis.
  • Replay attack: Packet encryption does not by itself establish peer identity or guarantee application messages are processed only once. Applications that need these properties should use an authenticated protocol and implement appropriate replay protection.

6. Packet Clocking

  1. Immediate flush on window progress or fast retransmit: Flush pending data when acknowledgments advance the send window or trigger fast retransmission, without waiting for the next periodic update.
  2. ACK clocking: Flush ACKs when the pending ACK list reaches approximately one MTU's worth of ACK segments, rather than waiting for the periodic update. In high-speed networks, this acts as a higher-frequency "clock signal," potentially boosting unidirectional transmission speed by approximately 6x. For instance, if a batch takes only 1.5ms to process on a high-speed link but still adheres to a fixed 10ms transmission cycle, the actual throughput would be limited to 1/6 of the potential.
  3. Packet batching: The session packet-processing path batches outgoing packets and uses platform-specific batched I/O where available. This can reduce syscall overhead; it is not a packet pacing mechanism.
  4. Data structures: The snd_buf ring buffer supports cache-friendly sequential traversal. Retransmission checks are O(n) in the number of in-flight segments, so very large windows can increase per-update work.

Ultimately, nothing is more critical in a transmission system than the clock (real-time performance).

7. FEC Design Characteristics

  • Reed-Solomon encoding and decoding are performed in the outgoing and incoming packet-processing paths.
  • Data/parity ratios are configurable per session. More parity can recover more packet loss, at the cost of additional bandwidth; the overhead depends on the configured ratio.
  • Encoder and decoder buffers are reused where possible to reduce allocations; actual memory use depends on traffic and configuration.
  • When enough shards arrive, the decoder attempts to reconstruct missing data packets and passes recovered packets to KCP for normal processing.
  • The receiver detects a sender/receiver shard-configuration mismatch from incoming data and parity packet sequence patterns. Once it has enough consecutive samples to identify both shard counts, it rebuilds its decoder and discards shards buffered under the old configuration. Detection tolerates missing or duplicate samples, but may take longer when packets are lost or reordered. The detected configuration is accepted only when the total number of data and parity shards is at most 256.
  • When packet encryption is enabled, FEC headers are included in the encrypted packet. AEAD authenticates packet contents; non-AEAD modes with CRC-32 do not provide cryptographic authentication.

Specification

Frame Format
NONCE:
  Per-packet nonce; its size depends on the encryption mode (16 bytes for
  the legacy mode, or the configured AEAD nonce size).
  
CRC32:
  IEEE CRC-32 checksum used by non-AEAD modes; AEAD uses an authentication tag.
 
FEC TYPE:
  typeData = 0xF1
  typeParity = 0xF2
  
FEC SEQID:
  Increments modulo (0xffffffff/shardSize) * shardSize; valid IDs are in
  [0, (0xffffffff/shardSize) * shardSize - 1].
  
SIZE:
  Number of bytes from the 2-byte SIZE field through the end of the packet:
  the KCP frame plus 2 bytes. The payload after the SIZE field is SIZE-2 bytes.

KCP Header
+------------------------------+
|           conv (u32)         |
+-------+-------+--------------+
|  cmd  |  frag |     wnd      |
|  u8   |  u8   |     u16      |
+------------------------------+
|           ts   (u32)         |
+------------------------------+
|           sn   (u32)         |
+------------------------------+
|           una  (u32)         |
+------------------------------+
|           data (bytes)       |
+------------------------------+

Performance

The results below are historical and hardware-specific, not performance guarantees. Run go test -run='^$' -bench . on your target system for comparable measurements. Expand a section to see the raw output.

Linux amd64 — AMD Ryzen 9 5950X
goos: linux
goarch: amd64
pkg: github.com/xtaci/kcp-go/v5
cpu: AMD Ryzen 9 5950X 16-Core Processor
BenchmarkPacketBufferPoolGetPut
BenchmarkPacketBufferPoolGetPut/ArrayPointer
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Serial
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Serial-32          98010116                12.37 ns/op            0 B/op         0 allocs/op
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Parallel
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Parallel-32                1000000000               0.7148 ns/op          0 B/op          0 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice
BenchmarkPacketBufferPoolGetPut/Slice/Serial
BenchmarkPacketBufferPoolGetPut/Slice/Serial-32                         37707745                27.47 ns/op           24 B/op          1 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice/Parallel
BenchmarkPacketBufferPoolGetPut/Slice/Parallel-32                       81515508                14.07 ns/op           24 B/op          1 allocs/op
BenchmarkConnManagerAllocs
BenchmarkConnManagerAllocs-32                                           28268137                41.17 ns/op           17 B/op          2 allocs/op
BenchmarkConnManagerImplAllocs
BenchmarkConnManagerImplAllocs-32                                       39315105                29.40 ns/op            0 B/op          0 allocs/op
BenchmarkSM4
BenchmarkSM4-32                                                            60841             19203 ns/op         153.31 MB/s           0 B/op          0 allocs/op
BenchmarkAES128
BenchmarkAES128-32                                                        559143              2145 ns/op        1372.49 MB/s           0 B/op          0 allocs/op
BenchmarkAES192
BenchmarkAES192-32                                                        475938              2442 ns/op        1205.33 MB/s           0 B/op          0 allocs/op
BenchmarkAES256
BenchmarkAES256-32                                                        455337              2633 ns/op        1118.05 MB/s           0 B/op          0 allocs/op
BenchmarkTEA
BenchmarkTEA-32                                                           141236              8534 ns/op         344.97 MB/s           0 B/op          0 allocs/op
BenchmarkXOR
BenchmarkXOR-32                                                         24354942                49.34 ns/op     59669.95 MB/s          0 B/op          0 allocs/op
BenchmarkBlowfish
BenchmarkBlowfish-32                                                       71466             16737 ns/op         175.89 MB/s           0 B/op          0 allocs/op
BenchmarkNone
BenchmarkNone-32                                                        52308901                23.10 ns/op     127424.75 MB/s         0 B/op          0 allocs/op
BenchmarkCast5
BenchmarkCast5-32                                                          65563             18238 ns/op         161.42 MB/s           0 B/op          0 allocs/op
Benchmark3DES
Benchmark3DES-32                                                           18531             64510 ns/op          45.64 MB/s           0 B/op          0 allocs/op
BenchmarkTwofish
BenchmarkTwofish-32                                                        55621             21628 ns/op         136.12 MB/s           0 B/op          0 allocs/op
BenchmarkXTEA
BenchmarkXTEA-32                                                           46226             25930 ns/op         113.54 MB/s           0 B/op          0 allocs/op
BenchmarkSalsa20
BenchmarkSalsa20-32                                                       574081              2006 ns/op        1467.64 MB/s           0 B/op          0 allocs/op
BenchmarkCRC32
BenchmarkCRC32-32                                                       20230149                58.73 ns/op     17436.55 MB/s
BenchmarkCFB_AES_128_CRC32
BenchmarkCFB_AES_128_CRC32-32                                             982596              1220 ns/op        1147.27 MB/s
BenchmarkAEAD_AES_128_GCM
BenchmarkAEAD_AES_128_GCM-32                                             4050789               297.7 ns/op      4702.75 MB/s
BenchmarkCFB_Salsa20_CRC32
BenchmarkCFB_Salsa20_CRC32-32                                            1000000              1008 ns/op        1389.40 MB/s
BenchmarkAEAD_Chacha20_Poly1035
BenchmarkAEAD_Chacha20_Poly1035-32                                       2515954               476.0 ns/op      2941.38 MB/s
BenchmarkCsprngSystem
BenchmarkCsprngSystem-32                                                 2676769               448.1 ns/op        35.71 MB/s
BenchmarkCsprngAES128
BenchmarkCsprngAES128-32                                                81380560                14.79 ns/op     1082.14 MB/s
BenchmarkCsprngChacha8
BenchmarkCsprngChacha8-32                                               99872712                12.03 ns/op      664.95 MB/s
BenchmarkFECDecode
BenchmarkFECDecode-32                                                    3835436               315.0 ns/op      4673.44 MB/s         246 B/op          1 allocs/op
BenchmarkFECEncode
BenchmarkFECEncode-32                                                    6003200               200.2 ns/op      7353.66 MB/s           2 B/op          0 allocs/op
BenchmarkFlush
BenchmarkFlush-32                                                         367267              3268 ns/op               0 B/op          0 allocs/op
BenchmarkDebugLog
BenchmarkDebugLog-32                                                    1000000000               1.042 ns/op
BenchmarkEchoSpeed4K
BenchmarkEchoSpeed4K-32                                                    53157             22127 ns/op         185.11 MB/s        1772 B/op         22 allocs/op
BenchmarkEchoSpeed64K
BenchmarkEchoSpeed64K-32                                                    3157            346416 ns/op         189.18 MB/s       27677 B/op        358 allocs/op
BenchmarkEchoSpeed512K
BenchmarkEchoSpeed512K-32                                                    426           2787072 ns/op         188.11 MB/s      222284 B/op       2843 allocs/op
BenchmarkEchoSpeed1M
BenchmarkEchoSpeed1M-32                                                      208           5521962 ns/op         189.89 MB/s      449980 B/op       5684 allocs/op
BenchmarkSinkSpeed4K
BenchmarkSinkSpeed4K-32                                                   126181             10293 ns/op         397.93 MB/s         316 B/op          6 allocs/op
BenchmarkSinkSpeed64K
BenchmarkSinkSpeed64K-32                                                    7675            164723 ns/op         397.86 MB/s        5182 B/op         97 allocs/op
BenchmarkSinkSpeed256K
BenchmarkSinkSpeed256K-32                                                    994           1209617 ns/op         433.43 MB/s       41641 B/op        777 allocs/op
BenchmarkSinkSpeed1M
BenchmarkSinkSpeed1M-32                                                      448           2627570 ns/op         399.07 MB/s       90851 B/op       1551 allocs/op
BenchmarkTimedFuncHeap
BenchmarkTimedFuncHeap-32                                               13520214                88.25 ns/op            0 B/op          0 allocs/op
PASS
ok      github.com/xtaci/kcp-go/v5      51.387s
macOS arm64 — Apple M4 Pro
macOS 26.7.3
Apple M4 Pro
12 CPUs, 24 GiB memory
Go 1.27.4

$ go test -run='^$' -bench . -benchmem -count=1
goos: darwin
goarch: arm64
pkg: github.com/xtaci/kcp-go/v5
cpu: Apple M4 Pro
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Serial-12  	183539385	         6.432 ns/op	       0 B/op	       0 allocs/op
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Parallel-12         	1000000000	         0.8019 ns/op	       0 B/op	       0 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice/Serial-12                  	80577022	        13.55 ns/op	      24 B/op	       1 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice/Parallel-12                	143337536	         8.575 ns/op	      24 B/op	       1 allocs/op
BenchmarkConnManagerAllocs-12                                    	53025882	        21.56 ns/op	      17 B/op	       2 allocs/op
BenchmarkConnManagerImplAllocs-12                                	95109146	        12.82 ns/op	       0 B/op	       0 allocs/op
BenchmarkSM4-12                                                  	   66414	     18070 ns/op	 162.93 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES128-12                                               	  794239	      1510 ns/op	1949.97 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES192-12                                               	  743060	      1615 ns/op	1823.37 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES256-12                                               	  681664	      1750 ns/op	1682.12 MB/s	       0 B/op	       0 allocs/op
BenchmarkTEA-12                                                  	  165542	      7192 ns/op	 409.32 MB/s	       0 B/op	       0 allocs/op
BenchmarkXOR-12                                                  	29704960	        40.67 ns/op	72385.73 MB/s	       0 B/op	       0 allocs/op
BenchmarkBlowfish-12                                             	   85344	     14004 ns/op	 210.23 MB/s	       0 B/op	       0 allocs/op
BenchmarkNone-12                                                 	48431604	        24.73 ns/op	119041.32 MB/s	       0 B/op	       0 allocs/op
BenchmarkCast5-12                                                	   83814	     14178 ns/op	 207.64 MB/s	       0 B/op	       0 allocs/op
Benchmark3DES-12                                                 	   21549	     55677 ns/op	  52.88 MB/s	       0 B/op	       0 allocs/op
BenchmarkTwofish-12                                              	   66288	     18091 ns/op	 162.73 MB/s	       0 B/op	       0 allocs/op
BenchmarkXTEA-12                                                 	   48271	     24919 ns/op	 118.14 MB/s	       0 B/op	       0 allocs/op
BenchmarkSalsa20-12                                              	  322832	      3680 ns/op	 800.02 MB/s	       0 B/op	       0 allocs/op
BenchmarkCRC32-12                                                	15187437	        79.03 ns/op	12956.84 MB/s	       0 B/op	       0 allocs/op
BenchmarkCFB_AES_128_CRC32-12                                    	 1298352	       924.7 ns/op	1514.03 MB/s	       0 B/op	       0 allocs/op
BenchmarkAEAD_AES_128_GCM-12                                     	 6335162	       189.4 ns/op	7390.19 MB/s	       0 B/op	       0 allocs/op
BenchmarkCFB_Salsa20_CRC32-12                                    	  638697	      1867 ns/op	 749.94 MB/s	       0 B/op	       0 allocs/op
BenchmarkAEAD_Chacha20_Poly1035-12                               	 1000000	      1132 ns/op	1236.28 MB/s	       0 B/op	       0 allocs/op
BenchmarkCsprngSystem-12                                         	 7053890	       171.6 ns/op	  93.26 MB/s	       0 B/op	       0 allocs/op
BenchmarkCsprngAES128-12                                         	100000000	        10.19 ns/op	1569.91 MB/s	       0 B/op	       0 allocs/op
BenchmarkCsprngChacha8-12                                        	139098945	         8.617 ns/op	 928.36 MB/s	       0 B/op	       0 allocs/op
BenchmarkFECDecode-12                                            	 6912384	       170.9 ns/op	8612.18 MB/s	     245 B/op	       1 allocs/op
BenchmarkFECEncode-12                                            	 7130154	       168.2 ns/op	8752.22 MB/s	       2 B/op	       0 allocs/op
BenchmarkFlush-12                                                	  626137	      1727 ns/op	       0 B/op	       0 allocs/op
BenchmarkDebugLog-12                                             	760116879	         1.578 ns/op	       0 B/op	       0 allocs/op
BenchmarkEchoSpeed4K-12                                          	   15106	     79711 ns/op	  51.39 MB/s	    2821 B/op	      41 allocs/op
BenchmarkEchoSpeed64K-12                                         	    1159	   1090530 ns/op	  60.10 MB/s	   38344 B/op	     567 allocs/op
BenchmarkEchoSpeed512K-12                                        	     139	   8656694 ns/op	  60.56 MB/s	  317701 B/op	    4515 allocs/op
BenchmarkEchoSpeed1M-12                                          	      93	  17486371 ns/op	  59.97 MB/s	  683001 B/op	    9089 allocs/op
BenchmarkSinkSpeed4K-12                                          	   62803	     18231 ns/op	 224.68 MB/s	     462 B/op	       6 allocs/op
BenchmarkSinkSpeed64K-12                                         	    4075	    289811 ns/op	 226.13 MB/s	    7419 B/op	      97 allocs/op
BenchmarkSinkSpeed256K-12                                        	     562	   2299120 ns/op	 228.04 MB/s	   55895 B/op	     775 allocs/op
BenchmarkSinkSpeed1M-12                                          	     237	   4684709 ns/op	 223.83 MB/s	  131504 B/op	    1547 allocs/op
BenchmarkTimedFuncHeap-12                                        	22095123	        53.56 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/xtaci/kcp-go/v5	53.959s
Linux arm64 — Raspberry Pi 4
$ go test -v -run='^$' -bench .
goos: linux
goarch: arm64
pkg: github.com/xtaci/kcp-go/v5
BenchmarkPacketBufferPoolGetPut
BenchmarkPacketBufferPoolGetPut/ArrayPointer
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Serial
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Serial-4  	19112130	        61.81 ns/op	       0 B/op	       0 allocs/op
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Parallel
BenchmarkPacketBufferPoolGetPut/ArrayPointer/Parallel-4         	78086307	        15.33 ns/op	       0 B/op	       0 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice
BenchmarkPacketBufferPoolGetPut/Slice/Serial
BenchmarkPacketBufferPoolGetPut/Slice/Serial-4                  	 6565906	       186.1 ns/op	      24 B/op	       1 allocs/op
BenchmarkPacketBufferPoolGetPut/Slice/Parallel
BenchmarkPacketBufferPoolGetPut/Slice/Parallel-4                	22321516	        54.60 ns/op	      24 B/op	       1 allocs/op
BenchmarkConnManagerAllocs
BenchmarkConnManagerAllocs-4                                    	 3888459	       305.6 ns/op	      17 B/op	       2 allocs/op
BenchmarkConnManagerImplAllocs
BenchmarkConnManagerImplAllocs-4                                	 6677256	       179.2 ns/op	       0 B/op	       0 allocs/op
BenchmarkSM4
BenchmarkSM4-4                                                  	   18790	     63911 ns/op	  46.06 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES128
BenchmarkAES128-4                                               	   21913	     54753 ns/op	  53.77 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES192
BenchmarkAES192-4                                               	   18849	     63614 ns/op	  46.28 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES256
BenchmarkAES256-4                                               	   16566	     72443 ns/op	  40.64 MB/s	       0 B/op	       0 allocs/op
BenchmarkTEA
BenchmarkTEA-4                                                  	   33770	     35531 ns/op	  82.86 MB/s	       0 B/op	       0 allocs/op
BenchmarkXOR
BenchmarkXOR-4                                                  	 2232950	       519.5 ns/op	5667.11 MB/s	       0 B/op	       0 allocs/op
BenchmarkBlowfish
BenchmarkBlowfish-4                                             	   19405	     61841 ns/op	  47.61 MB/s	       0 B/op	       0 allocs/op
BenchmarkNone
BenchmarkNone-4                                                 	 4342510	       276.7 ns/op	10638.63 MB/s	       0 B/op	       0 allocs/op
BenchmarkCast5
BenchmarkCast5-4                                                	   18013	     66630 ns/op	  44.18 MB/s	       0 B/op	       0 allocs/op
Benchmark3DES
Benchmark3DES-4                                                 	    4147	    296576 ns/op	   9.93 MB/s	       0 B/op	       0 allocs/op
BenchmarkTwofish
BenchmarkTwofish-4                                              	   10000	    114816 ns/op	  25.64 MB/s	       0 B/op	       0 allocs/op
BenchmarkXTEA
BenchmarkXTEA-4                                                 	   10000	    112777 ns/op	  26.10 MB/s	       0 B/op	       0 allocs/op
BenchmarkSalsa20
BenchmarkSalsa20-4                                              	   42936	     27950 ns/op	 105.33 MB/s	       0 B/op	       0 allocs/op
BenchmarkCRC32
BenchmarkCRC32-4                                                	 6691806	       184.1 ns/op	5561.39 MB/s
BenchmarkCFB_AES_128_CRC32
BenchmarkCFB_AES_128_CRC32-4                                    	   46272	     25938 ns/op	  53.98 MB/s
BenchmarkAEAD_AES_128_GCM
BenchmarkAEAD_AES_128_GCM-4                                     	   14922	     80422 ns/op	  17.41 MB/s
BenchmarkCFB_Salsa20_CRC32
BenchmarkCFB_Salsa20_CRC32-4                                    	   88452	     13558 ns/op	 103.26 MB/s
BenchmarkAEAD_Chacha20_Poly1035
BenchmarkAEAD_Chacha20_Poly1035-4                               	  133792	      8965 ns/op	 156.16 MB/s
BenchmarkCsprngSystem
BenchmarkCsprngSystem-4                                         	 3153832	       357.6 ns/op	  44.74 MB/s
BenchmarkCsprngAES128
BenchmarkCsprngAES128-4                                         	 3395547	       353.5 ns/op	  45.27 MB/s
BenchmarkCsprngChacha8
BenchmarkCsprngChacha8-4                                        	11190523	       107.2 ns/op	  74.60 MB/s
BenchmarkFECDecode
BenchmarkFECDecode-4                                            	  523029	      2079 ns/op	 708.19 MB/s	     246 B/op	       1 allocs/op
BenchmarkFECEncode
BenchmarkFECEncode-4                                            	  571377	      2186 ns/op	 673.41 MB/s	       2 B/op	       0 allocs/op
BenchmarkFlush
BenchmarkFlush-4                                                	   86679	     13829 ns/op	       0 B/op	       0 allocs/op
BenchmarkDebugLog
BenchmarkDebugLog-4                                             	206342220	         5.804 ns/op
BenchmarkEchoSpeed4K
BenchmarkEchoSpeed4K-4                                          	    5937	    199945 ns/op	  20.49 MB/s	    3136 B/op	      27 allocs/op
BenchmarkEchoSpeed64K
BenchmarkEchoSpeed64K-4                                         	     332	   3273746 ns/op	  20.02 MB/s	   45978 B/op	     436 allocs/op
BenchmarkEchoSpeed512K
BenchmarkEchoSpeed512K-4                                        	      44	  27707225 ns/op	  18.92 MB/s	  480992 B/op	    3727 allocs/op
BenchmarkEchoSpeed1M
BenchmarkEchoSpeed1M-4                                          	      22	  52303019 ns/op	  20.05 MB/s	 1051987 B/op	    7221 allocs/op
BenchmarkSinkSpeed4K
BenchmarkSinkSpeed4K-4                                          	   29979	     39688 ns/op	 103.20 MB/s	     871 B/op	       6 allocs/op
BenchmarkSinkSpeed64K
BenchmarkSinkSpeed64K-4                                         	    1743	    674399 ns/op	  97.18 MB/s	   14168 B/op	      97 allocs/op
BenchmarkSinkSpeed256K
BenchmarkSinkSpeed256K-4                                        	     236	   5448550 ns/op	  96.23 MB/s	  110260 B/op	     778 allocs/op
BenchmarkSinkSpeed1M
BenchmarkSinkSpeed1M-4                                          	     100	  14779277 ns/op	  70.95 MB/s	  280937 B/op	    1563 allocs/op
BenchmarkTimedFuncHeap
BenchmarkTimedFuncHeap-4                                        	 2711781	       440.9 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/xtaci/kcp-go/v5	51.272s

Typical Flame Graph

Typical flame graph

Connection Termination and Multiplexing

KCP does not define TCP-style connection setup and teardown messages such as SYN/FIN/RST. Use an application-level keepalive/heartbeat when needed. smux can multiplex logical streams over a KCP session and provides its own keepalive mechanism.

Multiplexing also affects congestion behavior. KCP's congestion control is maintained per session, so logical streams carried by one smux connection share that session's congestion window and loss response. Opening a separate KCP session for every logical stream creates independent congestion controllers; over the same bottleneck, these sessions may compete with one another and collectively use more bandwidth. smux itself is not a network congestion controller: it multiplexes streams over the KCP transport.

The trade-off is that KCP delivers an ordered byte stream. Packet loss can therefore delay delivery to all smux streams sharing that session, even if some streams' data arrived successfully. Multiplex streams over one session when they should share transport and congestion state; use separate sessions when isolation is more important, while accounting for their independent congestion behavior.

FAQ

Q: I'm handling thousands of connections on my server, and CPU utilization is high.

A: Profile the workload and consider separating KCP traffic into a dedicated service. If the session is currently using a short update interval (for example, 10 ms), increasing it (for example, to 40 ms) may reduce scheduling and update overhead, at the cost of response latency. The default KCP interval is 100 ms, so 40 ms is not an increase over the default. SetNoDelay takes (nodelay, intervalMs, fastResend, disableCongestionControl); for example, conn.SetNoDelay(1, 40, 1, 0) keeps congestion control enabled. Disabling congestion control can increase congestion on shared networks and should only be done when appropriate for the deployment.

Q: When should I enable FEC?

A: FEC can recover some packet losses without waiting for retransmission, which may reduce latency on lossy links. It adds bandwidth and processing overhead and cannot recover losses beyond the configured parity capacity. Benchmark with representative loss patterns and tune the data/parity ratio for your workload.

Q: Should I enable encryption?

A: If you need protection for KCP/FEC headers in addition to application data, configure packet encryption. Prefer AEAD when UDP-packet integrity and authentication are required. If the application already uses TLS, packet encryption is not a substitute for TLS; whether to enable the additional layer depends on your threat model and overhead requirements.

Who is using this?

  1. https://github.com/getlantern/lantern -- Lantern delivers fast access to the open Internet.
  2. https://github.com/smallnest/rpcx -- An RPC service framework based on net/rpc, similar to Alibaba Dubbo and Weibo Motan.
  3. https://github.com/gonet2/agent -- A gateway for games with stream multiplexing.
  4. https://github.com/syncthing/syncthing -- Open Source Continuous File Synchronization.
  5. https://github.com/hanselime/paqet -- A bidirectional packet-level proxy built using raw sockets and KCP.

Looking for a C++ client?

  1. https://github.com/xtaci/libkcp -- FEC enhanced KCP session library for iOS/Android in C++

Examples

  1. simple examples
  1. https://github.com/xtaci/smux/ -- A Stream Multiplexing Library for golang with least memory
  2. https://github.com/xtaci/libkcp -- FEC enhanced KCP session library for iOS/Android in C++
  3. https://github.com/skywind3000/kcp -- A Fast and Reliable ARQ Protocol
  4. https://github.com/klauspost/reedsolomon -- Reed-Solomon Erasure Coding in Go

Documentation

Overview

When the debug build tag is not set, debugLog is a no-op and guarded calls can be eliminated at compile time.

Package kcp is a reliable UDP library for Go.

It provides reliable, ordered, error-checked byte-stream delivery over UDP, with optional FEC and packet encryption. Its API is compatible with net.Conn while providing additional transport controls.

Index

Constants

View Source
const (
	// Retransmission Timeout (RTO) bounds, in milliseconds
	IKCP_RTO_NDL = 30    // no-delay mode: minimum RTO (ms)
	IKCP_RTO_MIN = 100   // normal mode: minimum RTO (ms)
	IKCP_RTO_DEF = 200   // default RTO (ms)
	IKCP_RTO_MAX = 60000 // maximum RTO (ms), 60 seconds

	// Command types for the KCP segment header (cmd field)
	IKCP_CMD_PUSH = 81 // cmd: push data
	IKCP_CMD_ACK  = 82 // cmd: acknowledge
	IKCP_CMD_WASK = 83 // cmd: window probe request (ask)
	IKCP_CMD_WINS = 84 // cmd: window size response (tell)

	// Probe flags (bitfield), set in kcp.probe to schedule probe commands
	IKCP_ASK_SEND = 1 // schedule sending IKCP_CMD_WASK
	IKCP_ASK_TELL = 2 // schedule sending IKCP_CMD_WINS

	// Default window and MTU sizes
	IKCP_WND_SND = 32   // default send window size (packets)
	IKCP_WND_RCV = 32   // default receive window size (packets)
	IKCP_MTU_DEF = 1400 // default MTU (bytes, not including UDP/IP header)

	// Protocol parameters
	IKCP_ACK_FAST    = 3      // number of later ACKs needed to trigger fast retransmit
	IKCP_INTERVAL    = 100    // default flush interval (ms)
	IKCP_OVERHEAD    = 24     // per-segment header size: conv(4) + cmd(1) + frg(1) + wnd(2) + ts(4) + sn(4) + una(4) + len(4)
	IKCP_DEADLINK    = 20     // maximum transmissions before declaring the link dead
	IKCP_THRESH_INIT = 2      // initial slow-start threshold (packets)
	IKCP_THRESH_MIN  = 2      // minimum slow-start threshold (packets)
	IKCP_PROBE_INIT  = 500    // initial window probe timeout (ms)
	IKCP_PROBE_LIMIT = 120000 // maximum window probe timeout (ms), 120 seconds
	IKCP_SN_OFFSET   = 12     // byte offset of sequence number (sn) within the segment header
)

KCP Protocol Constants

View Source
const (
	RINGBUFFER_MIN = 8    // minimum backing-slice length
	RINGBUFFER_EXP = 1024 // backing-slice growth threshold: double below; add 10% at or above
)

Variables

This section is empty.

Functions

func Dial

func Dial(raddr string) (net.Conn, error)

Dial connects to the remote address "raddr" on the network "udp" without encryption and FEC

func Listen

func Listen(laddr string) (net.Listener, error)

Listen listens for incoming KCP packets addressed to the local address laddr on the network "udp",

func NewEntropy added in v5.6.48

func NewEntropy() io.Reader

NewEntropy creates a new entropy source.

func NewEntropyAES added in v5.6.48

func NewEntropyAES() io.Reader

NewEntropyAES creates a new AES-based entropy source.

func NewEntropyChacha8 added in v5.6.48

func NewEntropyChacha8() io.Reader

NewEntropyChacha8 creates a new ChaCha8-based entropy source.

func SetEntropy added in v5.6.48

func SetEntropy(r io.Reader)

SetEntropy sets the global entropy source used by fillRand.

Types

type BlockCrypt

type BlockCrypt interface {
	// Encrypt encrypts the whole block in src into dst.
	// Dst and src may point at the same memory.
	Encrypt(dst, src []byte)

	// Decrypt decrypts the whole block in src into dst.
	// Dst and src may point at the same memory.
	Decrypt(dst, src []byte)
}

BlockCrypt defines encryption/decryption methods for a given byte slice. Notes on implementing: the data to be encrypted contains a built-in nonce in its first 16 bytes.

func NewAEADCrypt added in v5.6.49

func NewAEADCrypt(aead cipher.AEAD) BlockCrypt

NewAEADCrypt creates an AEAD BlockCrypt instance from an existing cipher.AEAD

func NewAESGCMCrypt added in v5.6.49

func NewAESGCMCrypt(key []byte) (BlockCrypt, error)

NewAESGCMCrypt creates an AEAD BlockCrypt instance using AES-GCM The key must be 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func NewBlowfishBlockCrypt

func NewBlowfishBlockCrypt(key []byte) (BlockCrypt, error)

NewBlowfishBlockCrypt https://en.wikipedia.org/wiki/Blowfish_(cipher)

func NewCast5BlockCrypt

func NewCast5BlockCrypt(key []byte) (BlockCrypt, error)

NewCast5BlockCrypt https://en.wikipedia.org/wiki/CAST-128

func NewNoneBlockCrypt

func NewNoneBlockCrypt(key []byte) (BlockCrypt, error)

NewNoneBlockCrypt returns a BlockCrypt that copies data unchanged.

func NewSM4BlockCrypt

func NewSM4BlockCrypt(key []byte) (BlockCrypt, error)

NewSM4BlockCrypt https://github.com/tjfoc/gmsm/tree/master/sm4

func NewSalsa20BlockCrypt

func NewSalsa20BlockCrypt(key []byte) (BlockCrypt, error)

NewSalsa20BlockCrypt https://en.wikipedia.org/wiki/Salsa20

func NewSimpleXORBlockCrypt

func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error)

NewSimpleXORBlockCrypt creates an XOR BlockCrypt using a PBKDF2-expanded key.

func NewTripleDESBlockCrypt

func NewTripleDESBlockCrypt(key []byte) (BlockCrypt, error)

NewTripleDESBlockCrypt https://en.wikipedia.org/wiki/Triple_DES

func NewTwofishBlockCrypt

func NewTwofishBlockCrypt(key []byte) (BlockCrypt, error)

NewTwofishBlockCrypt https://en.wikipedia.org/wiki/Twofish

func NewXTEABlockCrypt

func NewXTEABlockCrypt(key []byte) (BlockCrypt, error)

NewXTEABlockCrypt https://en.wikipedia.org/wiki/XTEA

type FlushType added in v5.6.34

type FlushType int8
const (
	IKCP_FLUSH_ACKONLY FlushType = 1 << iota
	IKCP_FLUSH_FULL
)

type KCP

type KCP struct {
	// contains filtered or unexported fields
}

KCP defines a single KCP connection's protocol state machine. It is a pure ARQ (Automatic Repeat reQuest) implementation with no I/O.

func NewKCP

func NewKCP(conv uint32, output output_callback) *KCP

NewKCP creates a new KCP state machine.

conv must be the same at both endpoints, or data will be silently rejected.

The output function is called whenever data needs to be sent on the wire.

func (*KCP) Check

func (kcp *KCP) Check() uint32

(deprecated)

Check returns the elapsed-millisecond timestamp when Update should next be called. Scheduling updates this way avoids unnecessary calls and can help manage large numbers of KCP connections.

func (*KCP) Input

func (kcp *KCP) Input(data []byte, pktType PacketType, ackNoDelay bool) int

Input feeds a packet into the KCP state machine.

pktType distinguishes regular packets from packets recovered by FEC.

ackNoDelay causes pending ACKs to be flushed immediately, at the cost of increased bandwidth.

func (*KCP) NoDelay

func (kcp *KCP) NoDelay(nodelay, interval, resend, nc int) int

NoDelay configures no-delay mode, the update interval, fast retransmit, and congestion control. fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) nodelay: 0 disables (default); 1 enables interval: internal update interval in milliseconds (default 100 ms) resend: fast retransmit threshold; 0 disables it (default) nc: 0 enables congestion control (default); 1 disables it

func (*KCP) PeekSize

func (kcp *KCP) PeekSize() (length int)

PeekSize checks the size of next message in the recv queue

func (*KCP) Recv

func (kcp *KCP) Recv(buffer []byte) (n int)

Recv reads data from the KCP state machine.

It returns the number of bytes read.

It returns -1 when there is no readable data.

It returns -2 if len(buffer) is smaller than kcp.PeekSize().

func (*KCP) ResetRTO added in v5.7.4

func (kcp *KCP) ResetRTO()

ResetRTO resets the retransmission timeout (RTO) and resend timestamp for all segments currently in the send buffer.

This forces all unacknowledged segments to be eligible for immediate retransmission during the next flush.

func (*KCP) Send

func (kcp *KCP) Send(buffer []byte) int

Send sends data from the user level and returns a negative value on error.

func (*KCP) SetLogger added in v5.6.39

func (kcp *KCP) SetLogger(mask KCPLogType, logger logoutput_callback)

SetLogger configures the trace logger

func (*KCP) SetMtu

func (kcp *KCP) SetMtu(mtu int) int

SetMtu changes the MTU size. The default is 1400 bytes.

func (*KCP) Update

func (kcp *KCP) Update()

(deprecated)

Update advances the protocol state and flushes pending data. Call it periodically; use Check to determine when the next call is due. Internal timestamps are in milliseconds.

func (*KCP) WaitSnd

func (kcp *KCP) WaitSnd() int

WaitSnd returns the number of segments in the send buffer and send queue.

func (*KCP) WndSize

func (kcp *KCP) WndSize(sndwnd, rcvwnd int) int

WndSize sets the send and receive window sizes. The defaults are 32 segments for each.

type KCPLogType added in v5.6.39

type KCPLogType int32
const (
	IKCP_LOG_OUTPUT KCPLogType = 1 << iota
	IKCP_LOG_INPUT
	IKCP_LOG_SEND
	IKCP_LOG_RECV
	IKCP_LOG_OUT_ACK
	IKCP_LOG_OUT_PUSH
	IKCP_LOG_OUT_WASK
	IKCP_LOG_OUT_WINS
	IKCP_LOG_IN_ACK
	IKCP_LOG_IN_PUSH
	IKCP_LOG_IN_WASK
	IKCP_LOG_IN_WINS
)

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener accepts incoming connections.

func ListenWithOptions

func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error)

ListenWithOptions listens for incoming KCP packets addressed to laddr on the "udp" network, with optional packet encryption and FEC.

'block' is the block encryption algorithm to encrypt packets.

dataShards and parityShards specify the numbers of data and parity shards, respectively.

See https://github.com/klauspost/reedsolomon for details.

func ServeConn

func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error)

ServeConn serves the KCP protocol over a single packet connection. Packets with a nil source address or a nil *net.UDPAddr are ignored.

func (*Listener) Accept

func (l *Listener) Accept() (net.Conn, error)

Accept waits for and returns the next connection as a net.Conn.

func (*Listener) AcceptKCP

func (l *Listener) AcceptKCP() (*UDPSession, error)

AcceptKCP accepts a KCP connection

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the listener's network address. The returned address is shared by all invocations of Addr, so do not modify it.

func (*Listener) Close

func (l *Listener) Close() error

Close stops listening on the UDP address and closes the socket if the Listener owns it.

func (*Listener) Control added in v5.6.15

func (l *Listener) Control(f func(conn net.PacketConn) error) error

Control applies a function to the underlying packet connection. CAUTION: BE VERY CAREFUL TO USE THIS FUNCTION, YOU MAY BREAK THE PROTOCOL.

func (*Listener) SetDSCP

func (l *Listener) SetDSCP(dscp int) error

SetDSCP sets the 6-bit DSCP field in the IPv4 header or the 6-bit Traffic Class field in the IPv6 header.

If the underlying connection implements `SetDSCP(int) error`, SetDSCP invokes that method instead.

func (*Listener) SetDeadline

func (l *Listener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

func (*Listener) SetReadBuffer

func (l *Listener) SetReadBuffer(bytes int) error

SetReadBuffer sets the socket read buffer for the Listener

func (*Listener) SetReadDeadline

func (l *Listener) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*Listener) SetWriteBuffer

func (l *Listener) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the socket write buffer for the Listener

func (*Listener) SetWriteDeadline

func (l *Listener) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method. TODO: remove this method in the future, as it is not applicable to a Listener.

type OOBCallBackType added in v5.6.60

type OOBCallBackType func([]byte)

OOB callback function

type PacketPusher added in v5.7.1

type PacketPusher interface {
	SetPacketReceiver(fn func(b []byte, raddr net.Addr, err error))
}

PacketPusher is a net.PacketConn that can hand each received packet to a callback instead of being read. A client session or Listener on such a conn runs no read goroutine and processes each packet inside the callback, OOB handlers included, so a slow handler delays every conn the pusher serves.

The pusher must not call fn concurrently, just as one goroutine reads a conn. fn may modify b but must not keep it after returning. A non-nil err ends reads. Closing a client session or Listener sets a nil fn, which must remove the receiver. Closing a Listener also closes its accepted sessions. When err is nil, raddr must be a non-nil net.Addr. Packets with a nil source address or a nil *net.UDPAddr are ignored.

SetPacketReceiver is called with internal locks held. Implementations must not call back into kcp from inside SetPacketReceiver — no calls into the owning Listener or session, and no acquisition of any lock reachable from them. Doing so will deadlock.

type PacketType added in v5.6.40

type PacketType int8
const (
	IKCP_PACKET_REGULAR PacketType = iota
	IKCP_PACKET_FEC
)

type RingBuffer added in v5.6.22

type RingBuffer[T any] struct {
	// contains filtered or unexported fields
}

RingBuffer is a generic ring (circular) buffer that supports dynamic resizing. It provides efficient FIFO queue behavior with amortized constant time operations.

func NewRingBuffer added in v5.6.22

func NewRingBuffer[T any](size int) *RingBuffer[T]

NewRingBuffer creates a ring buffer with a backing slice of the specified size. One slot is reserved to distinguish full from empty, so MaxLen is size-1. Sizes of 8 or less use a backing slice of length 8.

func (*RingBuffer[T]) At added in v5.7.1

func (r *RingBuffer[T]) At(i int) *T

At returns the i-th element from the head. It allows indexed iteration without a closure, which TinyGo would allocate on every call.

func (*RingBuffer[T]) Clear added in v5.6.22

func (r *RingBuffer[T]) Clear()

Clear removes all elements and resets the ring to an empty state.

func (*RingBuffer[T]) Discard added in v5.6.22

func (r *RingBuffer[T]) Discard(n int) int

Discard discards the first N elements from the ring buffer. Returns the number of elements that are actually discarded (<= n). A non-positive N does not discard anything.

func (*RingBuffer[T]) ForEach added in v5.6.22

func (r *RingBuffer[T]) ForEach(fn func(*T) bool)

ForEach iterates over each element in the ring buffer, applying the provided function. If the function returns false, iteration stops early.

func (*RingBuffer[T]) ForEachReverse added in v5.6.22

func (r *RingBuffer[T]) ForEachReverse(fn func(*T) bool)

ForEachReverse iterates over each element in the ring buffer in reverse order, applying the provided function. If the function returns false, iteration stops early.

func (*RingBuffer[T]) IsEmpty added in v5.6.22

func (r *RingBuffer[T]) IsEmpty() bool

IsEmpty returns true if the ring has no elements.

func (*RingBuffer[T]) IsFull added in v5.6.22

func (r *RingBuffer[T]) IsFull() bool

IsFull returns true if advancing tail by one slot modulo the backing-slice length would make it equal to head.

func (*RingBuffer[T]) Len added in v5.6.22

func (r *RingBuffer[T]) Len() int

Len returns the number of elements currently in the ring.

func (*RingBuffer[T]) MaxLen added in v5.6.22

func (r *RingBuffer[T]) MaxLen() int

MaxLen returns the maximum number of elements the ring can hold. One backing slice slot is reserved to distinguish full from empty.

func (*RingBuffer[T]) Peek added in v5.6.22

func (r *RingBuffer[T]) Peek() (*T, bool)

Peek returns the element at the head of the ring without removing it. It returns the zero value and false if the ring is empty.

func (*RingBuffer[T]) Pop added in v5.6.22

func (r *RingBuffer[T]) Pop() (T, bool)

Pop removes and returns the element from the head of the ring. It returns the zero value and false if the ring is empty.

func (*RingBuffer[T]) Push added in v5.6.22

func (r *RingBuffer[T]) Push(v T)

Push adds an element to the tail of the ring. If the ring is full, it will grow automatically.

type Snmp

type Snmp struct {
	BytesSent           uint64 // application bytes sent
	BytesReceived       uint64 // application bytes received
	MaxConn             uint64 // max number of connections ever reached
	ActiveOpens         uint64 // accumulated active open connections
	PassiveOpens        uint64 // accumulated passive open connections
	CurrEstab           uint64 // current number of established connections
	InErrs              uint64 // UDP read errors reported from net.PacketConn
	InCsumErrors        uint64 // checksum errors from CRC32
	KCPInErrors         uint64 // packet input errors reported from KCP
	InPkts              uint64 // incoming packets count
	OutPkts             uint64 // outgoing packets count
	InSegs              uint64 // incoming KCP segments
	OutSegs             uint64 // outgoing KCP segments
	InBytes             uint64 // UDP bytes received
	OutBytes            uint64 // UDP bytes sent
	RetransSegs         uint64 // accumulated retransmitted segments
	FastRetransSegs     uint64 // accumulated fast retransmitted segments
	EarlyRetransSegs    uint64 // accumulated early retransmitted segments
	LostSegs            uint64 // number of segs inferred as lost
	RepeatSegs          uint64 // number of segs duplicated
	FECFullShardSet     uint64 // number of shard sets received with all data shards present
	FECRecovered        uint64 // number of packets recovered by FEC
	FECErrs             uint64 // number of FEC encoding or recovery errors
	FECParityShards     uint64 // number of FEC parity shards received
	FECShardSet         uint64 // number of shard sets that are not yet complete
	FECShardMin         uint64 // minimum shard ID among active FEC shard sets
	RingBufferSndQueue  uint64 // Len of segments in send queue ring buffer
	RingBufferRcvQueue  uint64 // Len of segments in receive queue ring buffer
	RingBufferSndBuffer uint64 // Len of segments in send buffer ring buffer
	OOBPackets          uint64 // number of OOB packets received
}

Snmp contains network statistics.

var DefaultSnmp *Snmp = newSnmp()

DefaultSnmp is the global KCP connection statistics collector

func (*Snmp) Copy

func (s *Snmp) Copy() *Snmp

Copy returns a copy of the current SNMP snapshot.

func (*Snmp) Header

func (s *Snmp) Header() []string

Header returns the names of all fields.

func (*Snmp) Reset

func (s *Snmp) Reset()

Reset sets all statistics to zero.

func (*Snmp) ToSlice

func (s *Snmp) ToSlice() []string

ToSlice returns the current SNMP information as a slice.

type TimedSched added in v5.5.0

type TimedSched struct {
	// contains filtered or unexported fields
}

TimedSched runs functions at given times on a few shard goroutines.

Put pushes onto a shard's heap under its lock and wakes the shard only when the new task is due before everything already queued there. A shard runs all tasks due within schedSlack per wakeup, outside its lock, so a task may Put itself again. Previously, each Put passed through a feeder goroutine and an unbuffered channel and reset a timer, causing several scheduling handoffs per task.

var SystemTimedSched *TimedSched = NewTimedSched(min(runtime.NumCPU(), 2))

SystemTimedSched is the library-level timed scheduler, shared by all sessions. It drives periodic KCP flush()/update() calls, avoiding one goroutine per session.

func NewTimedSched added in v5.5.0

func NewTimedSched(parallel int) *TimedSched

NewTimedSched starts a scheduler with parallel shards.

func (*TimedSched) Close added in v5.5.0

func (ts *TimedSched) Close()

Close stops the scheduler and waits for all shard goroutines to exit. Pending tasks are dropped.

func (*TimedSched) Put added in v5.5.0

func (ts *TimedSched) Put(f func(), deadline time.Time)

Put schedules f to run at deadline.

type UDPSession

type UDPSession struct {
	// contains filtered or unexported fields
}

UDPSession is a KCP session over UDP.

func DialWithOptions

func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error)

DialWithOptions connects to raddr on the "udp" network, with optional packet encryption and FEC.

'block' is the block encryption algorithm to encrypt packets.

dataShards and parityShards specify the numbers of data and parity shards, respectively.

See https://github.com/klauspost/reedsolomon for details.

func NewConn

func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error)

NewConn establishes a session that speaks KCP over a packet connection. Packets with a source address other than a non-nil *net.UDPAddr are ignored.

func NewConn2

func NewConn2(raddr net.Addr, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error)

NewConn2 establishes a session that speaks KCP over a packet connection. raddr must be a non-nil net.Addr. Packets with a nil source address are ignored.

func NewConn3 deprecated

func NewConn3(convid uint32, raddr net.Addr, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error)

NewConn3 establishes a session that speaks KCP over a packet connection. raddr must be a non-nil net.Addr. Packets with a nil source address are ignored.

TODO: Remove this function in the future. It is redundant with NewConn4, which provides the same functionality with an additional `ownConn` parameter to indicate whether the connection is owned by the caller or not.

Deprecated: Use NewConn4 instead. This function is retained for backward compatibility, but it is redundant with NewConn4 and may be removed in the future.

func NewConn4 added in v5.6.14

func NewConn4(convid uint32, raddr net.Addr, block BlockCrypt, dataShards, parityShards int, ownConn bool, conn net.PacketConn) (*UDPSession, error)

NewConn4 establishes a session that speaks KCP over a packet connection. raddr must be a non-nil net.Addr. Packets with a nil source address are ignored.

func (*UDPSession) Close

func (s *UDPSession) Close() error

Close discards unsent data and closes the connection without waiting for acknowledgments. It waits for active send processing to finish.

func (*UDPSession) Control added in v5.6.15

func (s *UDPSession) Control(f func(conn net.PacketConn) error) error

Control applies a function to the underlying packet connection. CAUTION: BE VERY CAREFUL TO USE THIS FUNCTION, YOU MAY BREAK THE PROTOCOL.

func (*UDPSession) GetConv

func (s *UDPSession) GetConv() uint32

GetConv returns the session's conversation ID.

func (*UDPSession) GetOOBMaxSize added in v5.6.60

func (s *UDPSession) GetOOBMaxSize() int

GetOOBMaxSize returns the maximum payload size for an OOB packet.

The returned value is the maximum number of bytes that can be carried as OOB data in a single packet, based on the current MTU and protocol layout.

If FEC is not enabled, OOB is unsupported and this function returns 0.

func (*UDPSession) GetRTO added in v5.5.13

func (s *UDPSession) GetRTO() uint32

GetRTO returns the session's current RTO.

func (*UDPSession) GetSRTT added in v5.5.15

func (s *UDPSession) GetSRTT() int32

GetSRTT returns the session's current smoothed RTT.

func (*UDPSession) GetSRTTVar added in v5.5.15

func (s *UDPSession) GetSRTTVar() int32

GetSRTTVar returns the session's current RTT variance.

func (*UDPSession) LocalAddr

func (s *UDPSession) LocalAddr() net.Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

func (*UDPSession) Read

func (s *UDPSession) Read(b []byte) (n int, err error)

Read implements net.Conn.

Buffered data is drained before reporting a closed session or socket read error.

func (*UDPSession) RemoteAddr

func (s *UDPSession) RemoteAddr() net.Addr

RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.

func (*UDPSession) ResetRTO added in v5.7.4

func (s *UDPSession) ResetRTO()

ResetRTO resets the retransmission timers for all pending segments.

This method does not trigger a synchronous flush. Retransmission will naturally occur at the next background update tick, governed by the `interval` configured via SetNoDelay (default 100ms).

It is intended for cases where the application knows connectivity has been restored and wants to resume data delivery without waiting for existing retransmission timers to expire.

func (*UDPSession) SendOOB added in v5.6.60

func (s *UDPSession) SendOOB(data []byte) error

SendOOB sends an out-of-band (OOB) data packet.

OOB packets:

  • Are unreliable: they are NOT retransmitted if lost.
  • Are unordered: delivery order is not guaranteed.
  • Are unacknowledged: no ACKs are generated.
  • Bypass the KCP reliable data path.
  • Reuse the FEC header layout for demultiplexing, but are NOT protected by FEC.

The OOB payload MUST fit into a single packet. If the payload is too large, an error is returned.

If the internal send queue is full, the OOB packet is dropped silently.

func (*UDPSession) SetACKNoDelay

func (s *UDPSession) SetACKNoDelay(nodelay bool)

SetACKNoDelay controls ACK flushing. When true, ACKs are flushed immediately.

func (*UDPSession) SetBucket added in v5.7.4

func (s *UDPSession) SetBucket(bucket *ratelimit.Bucket)

SetBucket limits the rate at which Write and WriteBuffers accept application bytes. Protocol overhead, retransmissions, and SendOOB traffic are not counted. A value of nil disables rate limiting.

func (*UDPSession) SetDSCP

func (s *UDPSession) SetDSCP(dscp int) error

SetDSCP sets the 6-bit DSCP field in the IPv4 header or the 6-bit Traffic Class field in the IPv6 header.

If the underlying connection implements `SetDSCP(int) error`, SetDSCP invokes that method instead.

It has no effect if it's accepted from Listener.

func (*UDPSession) SetDUP

func (s *UDPSession) SetDUP(dup int)

(deprecated)

SetDUP duplicates UDP packets sent by KCP.

func (*UDPSession) SetDeadline

func (s *UDPSession) SetDeadline(t time.Time) error

SetDeadline sets the session's read and write deadlines. A zero time value disables the deadlines.

func (*UDPSession) SetLogger added in v5.6.39

func (s *UDPSession) SetLogger(mask KCPLogType, logger logoutput_callback)

SetLogger configures the kcp trace logger

func (*UDPSession) SetMtu

func (s *UDPSession) SetMtu(mtu int) bool

SetMtu sets the maximum transmission unit, excluding the UDP header.

func (*UDPSession) SetNoDelay

func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int)

SetNoDelay sets the KCP no-delay options. https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration

func (*UDPSession) SetOOBHandler added in v5.6.60

func (s *UDPSession) SetOOBHandler(callback OOBCallBackType) error

SetOOBHandler registers a callback for receiving out-of-band (OOB) data.

OOB data is delivered unreliably and bypasses the KCP reliable data path. The callback is invoked synchronously from the KCP input processing path.

The callback MUST return quickly and MUST NOT perform any blocking operations. Blocking inside the callback will stall processing of all other KCP packets.

Passing a nil callback unregisters the current OOB callback.

OOB support requires FEC to be enabled, as the OOB packet format reuses the FEC header layout for demultiplexing.

func (*UDPSession) SetRateLimit added in v5.6.35

func (s *UDPSession) SetRateLimit(bps uint32)

SetRateLimit limits the rate at which Write and WriteBuffers accept application bytes. Protocol overhead, retransmissions, and SendOOB traffic are not counted. A value of 0 disables rate limiting.

func (*UDPSession) SetReadBuffer

func (s *UDPSession) SetReadBuffer(bytes int) error

SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener

func (*UDPSession) SetReadDeadline

func (s *UDPSession) SetReadDeadline(t time.Time) error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UDPSession) SetReadNotify added in v5.7.1

func (s *UDPSession) SetReadNotify(fn func())

SetReadNotify sets fn to be called whenever data may have become ready for TryRead, and when the session closes or its socket fails. fn runs with the session locked, so it must not block or call into the session.

func (*UDPSession) SetStreamMode deprecated

func (s *UDPSession) SetStreamMode(enable bool)

Deprecated: toggles the stream mode on/off

func (*UDPSession) SetWindowSize

func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int)

SetWindowSize sets the maximum window sizes.

func (*UDPSession) SetWriteBuffer

func (s *UDPSession) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the socket write buffer, no effect if it's accepted from Listener

func (*UDPSession) SetWriteDeadline

func (s *UDPSession) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UDPSession) SetWriteDelay

func (s *UDPSession) SetWriteDelay(delay bool)

SetWriteDelay delays writes during bulk transfer until the next update interval.

func (*UDPSession) TryRead added in v5.7.1

func (s *UDPSession) TryRead(b []byte) (int, error)

TryRead is Read without waiting. It returns 0 and no error when no data is ready, and the session's error once it is closed or its socket failed and no data is left.

ReadDeadline is not applied for TryRead.

func (*UDPSession) Write

func (s *UDPSession) Write(b []byte) (n int, err error)

Write implements net.Conn

func (*UDPSession) WriteBuffers

func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error)

WriteBuffers writes a vector of byte slices to the underlying connection.

Directories

Path Synopsis
internal
lib/net/netip
Package netip defines an IP address type that's a small value type.
Package netip defines an IP address type that's a small value type.

Jump to

Keyboard shortcuts

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