kcp

package module
v2.0.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2016 License: MIT Imports: 25 Imported by: 2

README

kcp-go

GoDoc Powered MIT licensed Build Status Go Report Card Coverage Statusd

Claude_Shannon

Introduction

kcp-go is a full-featured reliable-UDP library for golang. It provides reliable, ordered, and error-checked delivery of a stream of octets between applications running on hosts communicating over an IP network.

Features

  1. Optimized for Real-Time Strategy Game.
  2. Compatible with skywind3000's C version with modifications.
  3. Cache friendly and Memory optimized design in golang.
  4. Compatible with net.Conn and net.Listener.
  5. FEC(Forward Error Correction) Support with Reed-Solomon Codes
  6. Packet level encryption support with AES, TEA, 3DES, Blowfish, Cast5, Salsa20, etc. in CFB mode.

Conventions

Control messages like SYN/FIN/RST in TCP are not defined in KCP, you need some keepalive mechanims in the application-level. a real world example is to use some multiplexing protocol over session, such as smux, see kcptun for example.

Documentation

For complete documentation, see the associated Godoc.

Specification

Frame Format

Usage

Client: full demo

kcpconn, err := kcp.DialWithOptions("192.168.0.1:10000", nil, 10, 3)

Server: full demo

lis, err := kcp.ListenWithOptions(":10000", nil, 10, 3)

Performance

  型号名称:	MacBook Pro
  型号标识符:	MacBookPro12,1
  处理器名称:	Intel Core i5
  处理器速度:	2.7 GHz
  处理器数目:	1
  核总数:	2
  L2 缓存(每个核):	256 KB
  L3 缓存:	3 MB
  内存:	8 GB
$ go test -run Speed
new client 127.0.0.1:61165
total recv: 16777216
time for 16MB rtt with encryption 570.41176ms
&{BytesSent:33554432 BytesReceived:33554432 MaxConn:2 ActiveOpens:1 PassiveOpens:1 CurrEstab:1 InErrs:0 InCsumErrors:0 InSegs:42577 OutSegs:42641 OutBytes:48111336 RetransSegs:92 FastRetransSegs:92 LostSegs:0 RepeatSegs:0 FECRecovered:1 FECErrs:0 FECSegs:8514}
PASS
ok  	github.com/xtaci/kcp-go	0.600s
  1. https://github.com/xtaci/libkcp -- Official client library for iOS/Android(C++11)
  2. https://github.com/skywind3000/kcp -- A Fast and Reliable ARQ Protocol
  3. https://github.com/klauspost/reedsolomon -- Reed-Solomon Erasure Coding in Go

Status

Production Ready

Donation

donate

All donations on this project will be used to support the development of gonet/2.

Documentation

Overview

Package kcp - A Fast and Reliable ARQ Protocol

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  = 7000   // 7 secs to probe window size
	IKCP_PROBE_LIMIT = 120000 // up to 120 secs to probe window
)

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"

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",

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 builtin nonce at the first 16 bytes

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 does nothing but copying

func NewSalsa20BlockCrypt

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

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

func NewSimpleXORBlockCrypt

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

NewSimpleXORBlockCrypt simple xor with key expanding

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 ConnectedUDPConn

type ConnectedUDPConn struct {
	*net.UDPConn
	Conn net.Conn // underlying connection if any
}

ConnectedUDPConn is a wrapper for net.UDPConn which converts WriteTo syscalls to Write syscalls that are 4 times faster on some OS'es. This should only be used for connections that were produced by a net.Dial* call.

func (*ConnectedUDPConn) WriteTo

func (c *ConnectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error)

WriteTo redirects all writes to the Write syscall, which is 4 times faster.

type FEC

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

FEC defines forward error correction for packets

type KCP

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

KCP defines a single KCP connection

func NewKCP

func NewKCP(conv uint32, output Output) *KCP

NewKCP create a new kcp control object, 'conv' must equal in two endpoint from the same connection.

func (*KCP) Check

func (kcp *KCP) Check(current uint32) uint32

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, update_ack bool) int

Input when you received a low level packet (eg. UDP packet), call it

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)

Recv is user/upper level recv: returns size, returns below zero for EAGAIN

func (*KCP) Send

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

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

func (*KCP) SetMtu

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

SetMtu changes MTU size, default is 1400

func (*KCP) Update

func (kcp *KCP) Update(current uint32)

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 Listener

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

Listener defines a server listening for connections

func ListenWithOptions

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

ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption, dataShards, parityShards defines Reed-Solomon Erasure Coding parameters

func ServeConn

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

ServeConn serves KCP protocol for a single packet connection.

func (*Listener) Accept

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

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic 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 Addr returned 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. Already Accepted connections are not closed.

func (*Listener) SetDSCP

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

SetDSCP sets the 6bit DSCP field of IP header

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.

type Output

type Output func(buf []byte, size int)

Output is a closure which captures conn and calls conn.Write

type Segment

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

Segment defines a KCP segment

type Snmp

type Snmp struct {
	BytesSent        uint64 // payload bytes sent
	BytesReceived    uint64
	MaxConn          uint64
	ActiveOpens      uint64
	PassiveOpens     uint64
	CurrEstab        uint64
	InErrs           uint64
	InCsumErrors     uint64 // checksum errors
	KCPInErrors      uint64 // packet iput error count from kcp
	InSegs           uint64
	OutSegs          uint64
	OutBytes         uint64 // udp bytes sent
	RetransSegs      uint64
	FastRetransSegs  uint64
	EarlyRetransSegs uint64
	LostSegs         uint64
	RepeatSegs       uint64
	FECRecovered     uint64
	FECErrs          uint64
	FECSegs          uint64 // fec segments 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

type UDPSession

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

UDPSession defines a KCP session implemented by UDP

func DialWithOptions

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

DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption

func NewConn

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

NewConn establishes a session and talks KCP protocol over a packet connection.

func (*UDPSession) Close

func (s *UDPSession) Close() error

Close closes the connection.

func (*UDPSession) GetConv

func (s *UDPSession) GetConv() uint32

GetConv gets conversation id of a session

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 the Conn Read method.

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

func (s *UDPSession) SetACKNoDelay(nodelay bool)

SetACKNoDelay changes ack flush option, set true to flush ack immediately,

func (*UDPSession) SetDSCP

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

SetDSCP sets the 6bit DSCP field of IP header, no effect if it's accepted from Listener

func (*UDPSession) SetDeadline

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

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

func (*UDPSession) SetKeepAlive

func (s *UDPSession) SetKeepAlive(interval int)

SetKeepAlive changes per-connection NAT keepalive interval; 0 to disable, default to 10s

func (*UDPSession) SetMtu

func (s *UDPSession) SetMtu(mtu int)

SetMtu sets the maximum transmission unit

func (*UDPSession) SetNoDelay

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

SetNoDelay calls nodelay() of kcp

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

func (s *UDPSession) SetStreamMode(enable bool)

SetStreamMode toggles the stream mode on/off

func (*UDPSession) SetWindowSize

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

SetWindowSize set maximum window size

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

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

Write implements the Conn Write method.

Jump to

Keyboard shortcuts

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