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
- func Dial(raddr string) (net.Conn, error)
- func Listen(laddr string) (net.Listener, error)
- func NewEntropy() io.Reader
- func NewEntropyAES() io.Reader
- func NewEntropyChacha8() io.Reader
- func SetEntropy(r io.Reader)
- type BlockCrypt
- func NewAEADCrypt(aead cipher.AEAD) BlockCrypt
- func NewAESBlockCrypt(key []byte) (BlockCrypt, error)
- func NewAESGCMCrypt(key []byte) (BlockCrypt, error)
- func NewBlowfishBlockCrypt(key []byte) (BlockCrypt, error)
- func NewCast5BlockCrypt(key []byte) (BlockCrypt, error)
- func NewNoneBlockCrypt(key []byte) (BlockCrypt, error)
- func NewSM4BlockCrypt(key []byte) (BlockCrypt, error)
- func NewSalsa20BlockCrypt(key []byte) (BlockCrypt, error)
- func NewSimpleXORBlockCrypt(key []byte) (BlockCrypt, error)
- func NewTEABlockCrypt(key []byte) (BlockCrypt, error)
- func NewTripleDESBlockCrypt(key []byte) (BlockCrypt, error)
- func NewTwofishBlockCrypt(key []byte) (BlockCrypt, error)
- func NewXTEABlockCrypt(key []byte) (BlockCrypt, error)
- type FlushType
- type KCP
- func (kcp *KCP) Check() uint32
- func (kcp *KCP) Input(data []byte, pktType PacketType, ackNoDelay bool) int
- func (kcp *KCP) NoDelay(nodelay, interval, resend, nc int) int
- func (kcp *KCP) PeekSize() (length int)
- func (kcp *KCP) Recv(buffer []byte) (n int)
- func (kcp *KCP) ResetRTO()
- func (kcp *KCP) Send(buffer []byte) int
- func (kcp *KCP) SetLogger(mask KCPLogType, logger logoutput_callback)
- func (kcp *KCP) SetMtu(mtu int) int
- func (kcp *KCP) Update()
- func (kcp *KCP) WaitSnd() int
- func (kcp *KCP) WndSize(sndwnd, rcvwnd int) int
- type KCPLogType
- type Listener
- func (l *Listener) Accept() (net.Conn, error)
- func (l *Listener) AcceptKCP() (*UDPSession, error)
- func (l *Listener) Addr() net.Addr
- func (l *Listener) Close() error
- func (l *Listener) Control(f func(conn net.PacketConn) error) error
- func (l *Listener) SetDSCP(dscp int) error
- func (l *Listener) SetDeadline(t time.Time) error
- func (l *Listener) SetReadBuffer(bytes int) error
- func (l *Listener) SetReadDeadline(t time.Time) error
- func (l *Listener) SetWriteBuffer(bytes int) error
- func (l *Listener) SetWriteDeadline(t time.Time) error
- type OOBCallBackType
- type PacketPusher
- type PacketType
- type RingBuffer
- func (r *RingBuffer[T]) At(i int) *T
- func (r *RingBuffer[T]) Clear()
- func (r *RingBuffer[T]) Discard(n int) int
- func (r *RingBuffer[T]) ForEach(fn func(*T) bool)
- func (r *RingBuffer[T]) ForEachReverse(fn func(*T) bool)
- func (r *RingBuffer[T]) IsEmpty() bool
- func (r *RingBuffer[T]) IsFull() bool
- func (r *RingBuffer[T]) Len() int
- func (r *RingBuffer[T]) MaxLen() int
- func (r *RingBuffer[T]) Peek() (*T, bool)
- func (r *RingBuffer[T]) Pop() (T, bool)
- func (r *RingBuffer[T]) Push(v T)
- type Snmp
- type TimedSched
- type UDPSession
- func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error)
- func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, ...) (*UDPSession, error)
- func NewConn2(raddr net.Addr, block BlockCrypt, dataShards, parityShards int, ...) (*UDPSession, error)
- func NewConn3(convid uint32, raddr net.Addr, block BlockCrypt, dataShards, parityShards int, ...) (*UDPSession, error)deprecated
- func NewConn4(convid uint32, raddr net.Addr, block BlockCrypt, dataShards, parityShards int, ...) (*UDPSession, error)
- func (s *UDPSession) Close() error
- func (s *UDPSession) Control(f func(conn net.PacketConn) error) error
- func (s *UDPSession) GetConv() uint32
- func (s *UDPSession) GetOOBMaxSize() int
- func (s *UDPSession) GetRTO() uint32
- func (s *UDPSession) GetSRTT() int32
- func (s *UDPSession) GetSRTTVar() int32
- func (s *UDPSession) LocalAddr() net.Addr
- func (s *UDPSession) Read(b []byte) (n int, err error)
- func (s *UDPSession) RemoteAddr() net.Addr
- func (s *UDPSession) ResetRTO()
- func (s *UDPSession) SendOOB(data []byte) error
- func (s *UDPSession) SetACKNoDelay(nodelay bool)
- func (s *UDPSession) SetBucket(bucket *ratelimit.Bucket)
- func (s *UDPSession) SetDSCP(dscp int) error
- func (s *UDPSession) SetDUP(dup int)
- func (s *UDPSession) SetDeadline(t time.Time) error
- func (s *UDPSession) SetLogger(mask KCPLogType, logger logoutput_callback)
- func (s *UDPSession) SetMtu(mtu int) bool
- func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int)
- func (s *UDPSession) SetOOBHandler(callback OOBCallBackType) error
- func (s *UDPSession) SetRateLimit(bps uint32)
- func (s *UDPSession) SetReadBuffer(bytes int) error
- func (s *UDPSession) SetReadDeadline(t time.Time) error
- func (s *UDPSession) SetReadNotify(fn func())
- func (s *UDPSession) SetStreamMode(enable bool)deprecated
- func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int)
- func (s *UDPSession) SetWriteBuffer(bytes int) error
- func (s *UDPSession) SetWriteDeadline(t time.Time) error
- func (s *UDPSession) SetWriteDelay(delay bool)
- func (s *UDPSession) TryRead(b []byte) (int, error)
- func (s *UDPSession) Write(b []byte) (n int, err error)
- func (s *UDPSession) WriteBuffers(v [][]byte) (n int, err error)
Constants ¶
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
const ( IKCP_LOG_OUTPUT_ALL = IKCP_LOG_OUTPUT | IKCP_LOG_OUT_ACK | IKCP_LOG_OUT_PUSH | IKCP_LOG_OUT_WASK | IKCP_LOG_OUT_WINS IKCP_LOG_INPUT_ALL = IKCP_LOG_INPUT | IKCP_LOG_IN_ACK | IKCP_LOG_IN_PUSH | IKCP_LOG_IN_WASK | IKCP_LOG_IN_WINS IKCP_LOG_ALL = IKCP_LOG_OUTPUT_ALL | IKCP_LOG_INPUT_ALL | IKCP_LOG_SEND | IKCP_LOG_RECV )
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 ¶
Dial connects to the remote address "raddr" on the network "udp" without encryption and FEC
func Listen ¶
Listen listens for incoming KCP packets addressed to the local address laddr on the network "udp",
func NewEntropy ¶ added in v5.6.48
NewEntropy creates a new entropy source.
func NewEntropyAES ¶ added in v5.6.48
NewEntropyAES creates a new AES-based entropy source.
func NewEntropyChacha8 ¶ added in v5.6.48
NewEntropyChacha8 creates a new ChaCha8-based entropy source.
func SetEntropy ¶ added in v5.6.48
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 NewAESBlockCrypt ¶
func NewAESBlockCrypt(key []byte) (BlockCrypt, error)
NewAESBlockCrypt https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
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 NewTEABlockCrypt ¶
func NewTEABlockCrypt(key []byte) (BlockCrypt, error)
NewTEABlockCrypt https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
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 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 ¶
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 ¶
(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 ¶
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) Recv ¶
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) SetLogger ¶ added in v5.6.39
func (kcp *KCP) SetLogger(mask KCPLogType, logger logoutput_callback)
SetLogger configures the trace logger
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.
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) AcceptKCP ¶
func (l *Listener) AcceptKCP() (*UDPSession, error)
AcceptKCP accepts a KCP connection
func (*Listener) 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 ¶
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 ¶
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 ¶
SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (*Listener) SetReadBuffer ¶
SetReadBuffer sets the socket read buffer for the Listener
func (*Listener) SetReadDeadline ¶
SetReadDeadline implements the Conn SetReadDeadline method.
func (*Listener) SetWriteBuffer ¶
SetWriteBuffer sets the socket write buffer for the Listener
type PacketPusher ¶ added in v5.7.1
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
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.
Source Files
¶
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. |
