github.com/shaoyuan1943/gokcp@v0.0.0-20201026071748-5b36d4c87f61/protocol.go (about)

     1  package gokcp
     2  
     3  import (
     4  	"time"
     5  	_ "unsafe"
     6  )
     7  
     8  const (
     9  	KCP_RTO_NDL       uint32 = 30    // no delay model min rto
    10  	KCP_RTO_MIN       uint32 = 100   // normal model min rto
    11  	KCP_RTO_DEF       uint32 = 200   // rto
    12  	KCP_RTO_MAX       uint32 = 60000 // max rto
    13  	KCP_CMD_PUSH      uint32 = 81    // cmd: push data to remote
    14  	KCP_CMD_ACK       uint32 = 82    // cmd: ack
    15  	KCP_CMD_WASK      uint32 = 83    // cmd: window probe(ask)
    16  	KCP_CMD_WINS      uint32 = 94    // cmd: window size(tell)
    17  	KCP_ASK_SEND      uint32 = 1     // need to send KCP_CMD_WASK
    18  	KCP_ASK_TELL      uint32 = 2     // need to send KCP_CMD_WINS
    19  	KCP_WND_SND       uint32 = 32    // send window size, uint package not bytes length
    20  	KCP_WND_RCV       uint32 = 128   // recv windows size, uint package not bytes length
    21  	KCP_MTU_DEF       uint32 = 1400  // mtu
    22  	KCP_ACK_FAST      uint32 = 3
    23  	KCP_INTERVAL      uint32 = 100 // update interval
    24  	KCP_OVERHEAD      uint32 = 24  // kcp package head size
    25  	KCP_DEADLINK      uint32 = 20
    26  	KCP_THRESH_INIT   uint32 = 2
    27  	KCP_THRESH_MIN    uint32 = 2
    28  	KCP_PROBE_INIT    uint32 = 5000   // 5 secs to probe window size
    29  	KCP_PROBE_LIMIT   uint32 = 100000 // up to 100 secs to probe window
    30  	KCP_FASTACK_LIMIT uint32 = 5      // max times to trigger fastack
    31  )
    32  
    33  type OutputCallback func(p []byte) error
    34  
    35  const PackBits = 32
    36  
    37  func unpackACK(ack uint64) (sn, ts uint32) {
    38  	const mask = 1<<PackBits - 1
    39  	sn = uint32((ack >> PackBits) & mask)
    40  	ts = uint32(ack & mask)
    41  	return
    42  }
    43  
    44  func packACK(sn, ts uint32) uint64 {
    45  	const mask = 1<<PackBits - 1
    46  	return (uint64(sn) << PackBits) | uint64(ts&mask)
    47  }
    48  
    49  func removeFront(p []*segment, count int) []*segment {
    50  	if count > len(p) {
    51  		p = p[:0]
    52  	} else {
    53  		p = p[count:]
    54  	}
    55  
    56  	return p
    57  }
    58  
    59  //go:linkname nanotime runtime.nanotime
    60  func nanotime() int64
    61  
    62  var kcpStartTime = nanotime()
    63  
    64  func SetupFromNowMS() uint32 {
    65  	return uint32((nanotime() - kcpStartTime) / (1000 * 1000))
    66  }
    67  
    68  func NowMS() int64 {
    69  	now := time.Now()
    70  	return now.Unix()*1000 + int64(now.Nanosecond()/1e6)
    71  }