kcp

package
v0.0.0-...-cc3858d Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

if build tag debug is not set, then debugLog will ingore in compile time

Index

Constants

View Source
const (
	IKCP_RTO_NDL     = 30  // no delay min rto
	IKCP_RTO_MIN     = 100 // normal min rto
	IKCP_RTO_DEF     = 200
	IKCP_RTO_MAX     = 60000
	IKCP_CMD_PUSH    = 81 // cmd: push data
	IKCP_CMD_ACK     = 82 // cmd: ack
	IKCP_CMD_WASK    = 83 // cmd: window probe (ask)
	IKCP_CMD_WINS    = 84 // cmd: window size (tell)
	IKCP_ASK_SEND    = 1  // need to send IKCP_CMD_WASK
	IKCP_ASK_TELL    = 2  // need to send IKCP_CMD_WINS
	IKCP_WND_SND     = 32
	IKCP_WND_RCV     = 32
	IKCP_MTU_DEF     = 1400
	IKCP_ACK_FAST    = 3
	IKCP_INTERVAL    = 100
	IKCP_OVERHEAD    = 24
	IKCP_DEADLINK    = 20
	IKCP_THRESH_INIT = 2
	IKCP_THRESH_MIN  = 2
	IKCP_PROBE_INIT  = 500    // 500ms to probe window size
	IKCP_PROBE_LIMIT = 120000 // up to 120 secs to probe window
	IKCP_SN_OFFSET   = 12
)
View Source
const (
	RINGBUFFER_MIN = 8
	RINGBUFFER_EXP = 1024
)

Variables

This section is empty.

Functions

This section is empty.

Types

type FlushType

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

func NewKCP

func NewKCP(conv uint32, output output_callback) *KCP

NewKCP create a new kcp state machine

'conv' must be equal in the connection peers, or else data will be silently rejected.

'output' function will be called whenever these is data to be sent on wire.

func (*KCP) Check

func (kcp *KCP) Check() uint32

(deprecated)

Check determines when should you invoke ikcp_update: returns when you should invoke ikcp_update in millisec, if there is no ikcp_input/_send calling. you can call ikcp_update in that time, instead of call update repeatly. Important to reduce unnacessary ikcp_update invoking. use it to schedule ikcp_update (eg. implementing an epoll-like mechanism, or optimize ikcp_update when handling massive kcp connections)

func (*KCP) Input

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

Input a packet into kcp state machine.

'regular' indicates it's a real data packet from remote, and it means it's not generated from ReedSolomon codecs.

'ackNoDelay' will trigger immediate ACK, but surely it will not be efficient in bandwidth

func (*KCP) NoDelay

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

NoDelay options fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) nodelay: 0:disable(default), 1:enable interval: internal update timer interval in millisec, default is 100ms resend: 0:disable fast resend(default), 1:enable fast resend nc: 0:normal congestion control(default), 1:disable congestion control

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)

Receive data from kcp state machine

Return number of bytes read.

Return -1 when there is no readable data.

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

func (*KCP) Send

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

Send is user/upper level send, returns below zero for error

func (*KCP) SetLogger

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 MTU size, default is 1400

func (*KCP) Update

func (kcp *KCP) Update()

(deprecated)

Update updates state (call it repeatedly, every 10ms-100ms), or you can ask ikcp_check when to call it again (without ikcp_input/_send calling). 'current' - current timestamp in millisec.

func (*KCP) WaitSnd

func (kcp *KCP) WaitSnd() int

WaitSnd gets how many packet is waiting to be sent

func (*KCP) WndSize

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

WndSize sets maximum window size: sndwnd=32, rcvwnd=32 by default

type KCPLogType

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 KcpOptions

type KcpOptions struct {
	KcpNoDelay        bool
	KcpNoCwnd         bool
	KcpUpdateInterval int // ms
	KcpFastResend     int
	KcpSendWnd        int
	KcpRecvWnd        int
	KcpMtu            int
	KcpMinRto         int // ms
	KcpStreamMode     bool
	ACKNoDelay        bool // kcp.Input 立即发送ack
}

type PacketType

type PacketType int8
const (
	IKCP_PACKET_REGULAR PacketType = iota
	IKCP_PACKET_FEC
)

type RingBuffer

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

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

NewRingBuffer creates a new Ring with a specified initial capacity. If the provided size is <= 8, it defaults to 8.

func (*RingBuffer[T]) Clear

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

Clear resets the ring to an empty state and reinitializes the buffer.

func (*RingBuffer[T]) Discard

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

func (*RingBuffer[T]) ForEach

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

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

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

IsEmpty returns true if the ring has no elements.

func (*RingBuffer[T]) IsFull

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

IsFull returns true if the ring buffer is full (tail + 1 == head).

func (*RingBuffer[T]) Len

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

Len returns the number of elements currently in the ring.

func (*RingBuffer[T]) MaxLen

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

MaxLen returns the maximum capacity of the ring buffer.

func (*RingBuffer[T]) Peek

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

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

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 Server

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

func NewServer

func NewServer(laddr string, opt *ServerOptions) (*Server, error)

func (*Server) Close

func (s *Server) Close() error

func (*Server) Run

func (s *Server) Run() error

type ServerOptions

type ServerOptions struct {
	KcpOptions
	// 对第一个udp消息进行验证,非法返回false, 成功需要返回SessionHandler, 会话id conv
	OnHandshake func(udpPacket []byte, raddr net.Addr) (sh SessionHandler, conv uint32, ok bool)
	// 解析连接唯一标识, 并且返回剩余bytes
	ParseConvId func(udpPacket []byte) (conv uint32, rest []byte)
}

type Session

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

func (*Session) Send

func (s *Session) Send(data []byte) error

type SessionHandler

type SessionHandler interface {
	//GetConnId() string
	// 连接成功回调
	OnConnect(*Session)
	// data为提交给用户层的数据, 返回true表示可以继续OnRead
	OnRead(data []byte) bool
	// 连接断开
	OnClose()
}

type Snmp

type Snmp struct {
	BytesSent           uint64 // bytes sent from upper level
	BytesReceived       uint64 // bytes received to upper level
	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 iput 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 // accmulated retransmited segments
	FastRetransSegs     uint64 // accmulated fast retransmitted segments
	EarlyRetransSegs    uint64 // accmulated early retransmitted segments
	LostSegs            uint64 // number of segs inferred as lost
	RepeatSegs          uint64 // number of segs duplicated
	FECFullShardSet     uint64 // number of FEC segments that are full
	FECRecovered        uint64 // correct packets recovered from FEC
	FECErrs             uint64 // incorrect packets recovered from FEC
	FECParityShards     uint64 // FEC segments received
	FECShardSet         uint64 // number of parity shards that are not yet received
	FECShardMin         uint64 // the minimum ID of FEC shards
	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 defines network statistics indicator

var DefaultSnmp *Snmp

DefaultSnmp is the global KCP connection statistics collector

func (*Snmp) Copy

func (s *Snmp) Copy() *Snmp

Copy make a copy of current snmp snapshot

func (*Snmp) Header

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

Header returns all field names

func (*Snmp) Reset

func (s *Snmp) Reset()

Reset values to zero

func (*Snmp) ToSlice

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

ToSlice returns current snmp info as slice

Jump to

Keyboard shortcuts

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