├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── README.en.md ├── README.md ├── benchmark.png ├── ikcp.c ├── ikcp.h ├── images ├── donation.png ├── spatialos-25.png └── spatialos-50.png ├── kcp.svg ├── protocol.txt ├── test.cpp └── test.h /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.obj 3 | *.exe 4 | *.dll 5 | *.so 6 | *.dylib 7 | *.ncb 8 | 9 | /.vscode/* 10 | /.idea/* 11 | /.DS_Store 12 | /.env 13 | /build/* 14 | 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | compiler: 3 | - gcc 4 | - clang 5 | script: 6 | - $CC -O3 test.cpp -o test -lstdc++ 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 3.10) 2 | 3 | project(kcp LANGUAGES C) 4 | 5 | include(CTest) 6 | include(GNUInstallDirs) 7 | 8 | cmake_policy(SET CMP0054 NEW) 9 | 10 | if(BUILD_SHARED_LIBS AND WIN32) 11 | set(exports_def_file "${CMAKE_CURRENT_BINARY_DIR}/exports.def") 12 | set(exports_def_contents 13 | "EXPORTS 14 | ikcp_create 15 | ikcp_release 16 | ikcp_setoutput 17 | ikcp_recv 18 | ikcp_send 19 | ikcp_update 20 | ikcp_check 21 | ikcp_input 22 | ikcp_flush 23 | ikcp_peeksize 24 | ikcp_setmtu 25 | ikcp_wndsize 26 | ikcp_waitsnd 27 | ikcp_nodelay 28 | ikcp_log 29 | ikcp_allocator 30 | ikcp_getconv 31 | ") 32 | 33 | file(WRITE "${exports_def_file}" "${exports_def_contents}") 34 | add_library(kcp ikcp.c "${exports_def_file}") 35 | else() 36 | add_library(kcp ikcp.c) 37 | endif() 38 | 39 | install(FILES ikcp.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") 40 | 41 | install(TARGETS kcp 42 | EXPORT kcp-targets 43 | ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" 44 | LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" 45 | RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" 46 | INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" 47 | ) 48 | 49 | install(EXPORT kcp-targets 50 | FILE kcp-config.cmake 51 | NAMESPACE kcp:: 52 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/kcp 53 | ) 54 | 55 | if(BUILD_TESTING) 56 | enable_language(CXX) 57 | 58 | add_executable(kcp_test test.cpp) 59 | if(MSVC AND NOT (MSVC_VERSION LESS 1900)) 60 | target_compile_options(kcp_test PRIVATE /utf-8) 61 | endif() 62 | endif() 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Lin Wei (skywind3000 at gmail.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 | KCP - A Fast and Reliable ARQ Protocol 2 | ====================================== 3 | 4 | [![Powered][3]][1] 5 | [![GitHub license][6]][7] 6 | [![Backers on Open Collective](https://opencollective.com/kcp/backers/badge.svg)](#backers) 7 | [![Sponsors on Open Collective](https://opencollective.com/kcp/sponsors/badge.svg)](#sponsors) 8 | 9 | [1]: https://github.com/skywind3000/kcp 10 | [2]: https://github.com/skywind3000/kcp/raw/master/kcp.svg 11 | [3]: https://github.com/skywind3000/kcp/raw/master/kcp.svg 12 | [4]: https://api.travis-ci.org/skywind3000/kcp.svg?branch=master 13 | [5]: https://travis-ci.org/skywind3000/kcp 14 | [6]: https://img.shields.io/badge/license-MIT-blue.svg 15 | [7]: https://github.com/skywind3000/kcp/blob/master/LICENSE 16 | 17 | # Introduction 18 | 19 | **KCP** is a high-performance, reliable transport protocol designed to significantly reduce latency compared to traditional TCP. It can achieve a **30–40% reduction in average latency** and up to three times lower maximum delay, _costing 10–20% additional bandwidth overhead_. 20 | 21 | KCP is implemented purely as an algorithm; it does not handle sending or receiving packets. It is designed to be transport-agnostic. Users must define their underlying transmission logic (e.g., via UDP) and pass data to KCP through callbacks. Even timekeeping is left to the user; KCP requires the current clock value to be provided externally, making it completely free of internal system calls. 22 | 23 | The protocol consists of two source files: **ikcp.h and ikcp.c**. These files are lightweight and easy to integrate into your existing network stack. Whether you're building a P2P system or a UDP-based protocol that needs a robust ARQ (Automatic Repeat reQuest) mechanism, you can start using KCP by adding these files to your project and writing a few lines of integration code. 24 | 25 | 26 | # Technical Specifications 27 | 28 | While TCP is optimized for throughput—maximizing the amount of data transmitted per second (e.g., kilobits/sec)—KCP is designed to focus on latency and packet delivery time. By prioritizing how quickly individual packets travel from sender to receiver, KCP trades 10–20% more bandwidth overhead for 30–40% faster transmission speed compared to TCP. 29 | 30 | Think of TCP as a wide canal: it can carry a large volume of data, but the flow is relatively slow. In contrast, KCP is like a narrow, fast-moving stream—it sends smaller amounts of data more quickly, ensuring lower delay and faster responsiveness. 31 | 32 | KCP supports both normal mode and fast mode, each optimizing performance based on different needs. Its increased flow rate is achieved through several key strategies: 33 | 34 | #### RTO Doubled vs Not Doubled: 35 | 36 | In TCP, retransmission timeout (RTO) increases exponentially—each failure doubles the timeout interval (RTO × 2). This means three consecutive losses can escalate to RTO × 8, leading to serious transmission delays. 37 | KCP, in contrast, uses a more responsive approach in fast mode: the RTO increases by a factor of 1.5x (based on empirical results), significantly improving recovery speed and reducing delay after packet loss. 38 | 39 | #### Selective Retransmission vs Full Retransmission: 40 | 41 | TCP often retransmits all subsequent data after a lost packet, which can lead to excessive redundancy. 42 | KCP implements selective retransmission, ensuring that only the actually lost packets are resent, minimizing unnecessary data transmission and improving efficiency. 43 | 44 | #### Fast Retransmission: 45 | 46 | When the sender transmits packets 1 through 5 and receives ACKs for 1, 3, 4, and 5, KCP deduces from missing ACK2 that packet 2 has likely been lost. After receiving multiple out-of-order ACKs, KCP can immediately trigger a fast retransmit of packet 2—without waiting for a timeout—drastically reducing retransmission latency under packet loss. 47 | 48 | #### Delayed ACK vs Non-delayed ACK: 49 | 50 | TCP often delays ACKs to optimize throughput, which can unintentionally inflate RTT calculations and delay loss detection—even with `NODELAY` settings. 51 | KCP provides configurable ACK behavior, allowing ACKs to be sent immediately when needed, enhancing responsiveness in latency-sensitive applications. 52 | 53 | #### UNA vs ACK+UNA: 54 | 55 | ARQ protocols typically use either: 56 | 57 | UNA (Unacknowledged Acknowledgment): Confirms all packets before a given sequence number (e.g., TCP). 58 | 59 | ACK: Confirms receipt of a specific packet. 60 | 61 | Each has tradeoffs: UNA can lead to full retransmissions, and standalone ACKs create overhead during loss. 62 | KCP combines both—each control message contains UNA info, and a dedicated ACK frame is used when necessary. This hybrid model increases reliability and precision without excess cost. 63 | 64 | #### Non-concessional Flow Control: 65 | By default, KCP follows TCP's fair flow control—factoring in send buffer size, receiver buffer, congestion control, and slow-start. 66 | However, for latency-critical small data, KCP can be configured to bypass congestion and slow-start, relying only on buffer sizes. This allows smooth transmission even under heavy network load (e.g., when BitTorrent is active), sacrificing some fairness for timeliness. 67 | 68 | 69 | # Quick Install 70 | 71 | You can download and install kcp using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: 72 | 73 | git clone https://github.com/Microsoft/vcpkg.git 74 | cd vcpkg 75 | ./bootstrap-vcpkg.sh 76 | ./vcpkg integrate install 77 | ./vcpkg install kcp 78 | 79 | Microsoft team members and community contributors keep the kcp port in vcpkg up to date. If the version is outdated, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. 80 | 81 | # Basic Usage 82 | 83 | 1. Create KCP object: 84 | 85 | ```cpp 86 | // Initialize the kcp object, conv is an integer that represents the session number, 87 | // same as the conv of tcp, both communication sides shall ensure the same conv, 88 | // so that mutual data packets can be recognized, user is a pointer which will be 89 | // passed to the callback function. 90 | ikcpcb *kcp = ikcp_create(conv, user); 91 | ``` 92 | 93 | 2. Set the callback function: 94 | 95 | ```cpp 96 | // KCP lower layer protocol output function, which will be called by KCP when it 97 | // needs to send data, buf/len represents the buffer and data length. 98 | // user refers to the incoming value at the time the kcp object is created to 99 | // distinguish between multiple KCP objects 100 | int udp_output(const char *buf, int len, ikcpcb *kcp, void *user) 101 | { 102 | .... 103 | } 104 | // Set the callback function 105 | kcp->output = udp_output; 106 | ``` 107 | 108 | 3. Call update in an interval: 109 | 110 | ```cpp 111 | // Call ikcp_update at a certain frequency to update the kcp state, and pass in 112 | // the current clock (in milliseconds). If the call is executed every 10ms, or 113 | // ikcp_check is used to determine time of the next call for update, no need to 114 | // call every time; 115 | ikcp_update(kcp, millisec); 116 | ``` 117 | 118 | 4. Input a lower layer data packet: 119 | 120 | ```cpp 121 | // Need to call when a lower layer data packet (such as UDP packet)is received: 122 | ikcp_input(kcp, received_udp_packet, received_udp_size); 123 | ``` 124 | 125 | After processing the output/input of the lower layer protocols, the KCP protocol can work normally. ikcp_send is used to send data to the remote end, while the other end uses ikcp_recv (kcp, ptr, size) to receive the data. 126 | 127 | 128 | # Protocol Configuration 129 | 130 | The protocol default mode is a standard ARQ, and various acceleration switches can be enabled by configuration: 131 | 132 | 1. Working Mode: 133 | ```cpp 134 | int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc) 135 | ``` 136 | 137 | - `nodelay`: Whether nodelay mode is enabled, 0 is not enabled; 1 enabled. 138 | - `interval` :P rotocol internal work interval, in milliseconds, such as 10 ms or 20 ms. 139 | - `resend` :Fast retransmission mode, 0 represents off by default, 2 can be set (2 ACK spans will result in direct retransmission) 140 | - `nc` : Whether to turn off flow control, 0 represents “Do not turn off” by default, 1 represents “Turn off”. 141 | - Normal Mode: ikcp_nodelay(kcp, 0, 40, 0, 0); 142 | - Turbo Mode: ikcp_nodelay(kcp, 1, 10, 2, 1); 143 | 144 | 2. Window Size: 145 | ```cpp 146 | int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd); 147 | ``` 148 | By default, the call will set the maximum send window and maximum receive window size of the procotol, 32. This can be understood as SND_BUF and RCV_BUF of TCP, but the unit is not the same, SND / RCV_BUF unit is byte, while this unit is the packet. 149 | 150 | 3. Maximum Transmission Unit: 151 | 152 | The algorithm protocol is not responsible for MTU detection. The default MTU is 1400 bytes, which can be set using ikcp_setmtu. The value will affect the maximum transmission unit upon data packet merging and fragmentation. 153 | 154 | 4. Minimum RTO: 155 | 156 | No matter TCP or KCP, they have the limitation for the minimum RTO when calculating the RTO, even if the calculated RTO is 40ms, as the default RTO is 100ms, the protocol can only detect packet loss after 100ms, which is 30ms in the fast mode, and the value can be manually changed: 157 | ```cpp 158 | kcp->rx_minrto = 10; 159 | ``` 160 | 161 | 162 | 163 | # Document Indexing 164 | 165 | Both the use and configuration of the protocol is straightforward, in most cases, after you read the above contents, you can use it. If you need further fine control, such as changing the KCP memory allocator, or if you need more efficient large-scale scheduling of KCP links (such as more than 3,500 links), or to better combine with TCP, you can continue the extensive reading: 166 | 167 | - [KCP Best Practice](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice-EN) 168 | - [Integration with the Existing TCP Server](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice-EN) 169 | - [Benchmarks](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark) 170 | 171 | 172 | # Related Applications 173 | 174 | - [kcptun](https://github.com/xtaci/kcptun): High-speed remote port forwarding based (tunnel) on kcp-go, with ssh-D, it allows smoother online video viewing than finalspeed. 175 | - [dog-tunnel](https://github.com/vzex/dog-tunnel): Network tunnel developed by GO, using KCP to greatly improve the transmission speed, and migrated a GO version of the KCP. 176 | - [v2ray](https://www.v2ray.com):Well-known proxy software, Shadowsocks replacement, integrated with kcp protocol after 1.17, using UDP transmission, no data packet features. 177 | - [HP-Socket](https://github.com/ldcsaa/HP-Socket): High Performance TCP/UDP/HTTP Communication Component. 178 | - [frp](https://github.com/fatedier/frp): A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet. 179 | - [asio-kcp](https://github.com/libinzhangyuan/asio_kcp): Use the complete UDP network library of KCP, complete implementation of UDP-based link state management, session control and KCP protocol scheduling, etc. 180 | - [kcp-cpp](https://github.com/Unit-X/kcp-cpp): Multi-platform (Windows, MacOS, Linux) C++ implementation of KCP as a simple library in your application. Contains socket handling and helper functions for all platforms. 181 | - [kcp-perl](https://github.com/Homqyy/kcp-perl): Perl extensions for kcp. It's OOP and Perl-Like. 182 | - [kcp-java](https://github.com/hkspirt/kcp-java):Implementation of Java version of KCP protocol. 183 | - [kcp-netty](https://github.com/szhnet/kcp-netty):Java implementation of KCP based on Netty. 184 | - [java-kcp](https://github.com/l42111996/java-Kcp): JAVA version KCP, based on netty implementation (including fec function) 185 | - [csharp-kcp](https://github.com/l42111996/csharp-kcp): csharp version KCP, based on dotNetty implementation (including fec function) 186 | - [kcp-go](https://github.com/xtaci/kcp-go): High-security GO language implementation of kcp, including simple implementation of UDP session management, as a base library for subsequent development. 187 | - [kcp-csharp](https://github.com/limpo1989/kcp-csharp): The csharp migration of kcp, containing the session management, which can access the above kcp-go server. 188 | - [KcpTransport](https://github.com/Cysharp/KcpTransport): KcpTransport is built on top of KCP ported to Pure C#, with implementations of Syn Cookie handshake, connection management, Unreliable communication, and KeepAlive. In the future, encryption will also be supported. 189 | - [Kcp-CSharp](https://github.com/Molth/Kcp-CSharp): a pure C# KCP instance callback(delegate) wrapper for (Unity/Godot/.NET) 190 | - [kcp2k](https://github.com/vis2k/kcp2k/): Line-by-line translation to C#, with optional Server/Client on top. 191 | - [kcp-rs](https://github.com/en/kcp-rs): The rust migration of KCP 192 | - [kcp-rust-native](https://github.com/b23r0/kcp-rust-native):KCP bindings for Rust 193 | - [lua-kcp](https://github.com/linxiaolong/lua-kcp): Lua extension of KCP, applicable for Lua server 194 | - [node-kcp](https://github.com/leenjewel/node-kcp): KCP interface for node-js 195 | - [nysocks](https://github.com/oyyd/nysocks): Nysocks provides proxy services base on libuv and kcp for nodejs users. Both SOCKS5 and ss protocols are supported in the client. 196 | - [shadowsocks-android](https://github.com/shadowsocks/shadowsocks-android): Shadowsocks for android has integrated kcptun using kcp protocol to accelerate shadowsocks, with good results 197 | - [kcpuv](https://github.com/elisaday/kcpuv): The kcpuv library developed with libuv, currently still in the early alpha phase. 198 | - [xkcptun](https://github.com/liudf0716/xkcptun): C language implementation of kcptun, embedded-friendly for [LEDE](https://github.com/lede-project/source) and [OpenWrt](https://github.com/openwrt/openwrt) projects. 199 | - [yasio](https://github.com/yasio/yasio): A cross-platform asynchronous socket library focus on any client application with kcp support, easy to use, API same with UDP and TCP, see [benchmark-pump](https://github.com/yasio/yasio/blob/master/benchmark.md). 200 | - [gouxp](https://github.com/shaoyuan1943/gouxp): Implementing a callback-based KCP development package with Go, with decryption and FEC support, is easy to use. 201 | - [kcp.py](https://github.com/RealistikDash/kcp.py): Python bindings and networking with an emphasis on dev friendliness. 202 | - [pykcp](https://github.com/enkiller/pykcp): KCP implementation for Python version. 203 | - [php-ext-kcp](https://github.com/wpjscc/php-ext-kcp): php extension for KCP. 204 | - [asio-kcp(new)](https://github.com/sniper00/asio-kcp): KCP implementation for C++/Asio, with Modern C++/Asio async features, such as coroutine. 205 | 206 | # Protocol Comparison 207 | 208 | If the network is never congested, KCP/TCP performance is similar; but the network itself is not reliable, and packet loss and jitter may be inevitable (otherwise why there are various reliable protocols). Compared in the intranet environment which is almost ideal, they have similar performance, but on the public Internet, under 3G / 4G network situation, or using the intranet packet loss simulation, the gap is obvious. The public network has an average of nearly 10% packet loss during peak times, which is even worse in wifi / 3g / 4g network, all of which will cause transmission congestion. 209 | 210 | Thanks to [zhangyuan](https://github.com/libinzhangyuan) the author of [asio-kcp](https://github.com/libinzhangyuan/asio_kcp) for the horizontal evaluation on KCP, enet and udt, and the conclusions are as follows: 211 | 212 | - ASIO-KCP **has good performace in wifi and phone network(3G, 4G)**. 213 | - The kcp is the **first choice for realtime pvp game**. 214 | - The lag is less than 1 second when network lag happen. **3 times better than enet** when lag happen. 215 | - The enet is a good choice if your game allow 2 second lag. 216 | - **UDT is a bad idea**. It always sink into badly situation of more than serval seconds lag. And the recovery is not expected. 217 | - enet has the problem of lack of doc. And it has lots of functions that you may intrest. 218 | - kcp's doc is in both chinese and english. Good thing is the function detail which is writen in code is english. And you can use asio_kcp which is a good wrap. 219 | - The kcp is a simple thing. You will write more code if you want more feature. 220 | - UDT has a perfect doc. UDT may has more bug than others as I feeling. 221 | 222 | For specifics please refer to: [Reliable Udp Benchmark](https://github.com/libinzhangyuan/reliable_udp_bench_mark) and [KCP-Benchmark](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark), for more guidance to the hesitant users. 223 | 224 | MMO Engine [SpatialOS](https://improbable.io/spatialOS) has a benchmark report on KCP/TCP/RakNet: 225 | 226 | ![](images/spatialos-50.png) 227 | 228 | for more details, please see the report itself: 229 | 230 | - [Kcp a new low latency secure network stack](https://improbable.io/blog/kcp-a-new-low-latency-secure-network-stack) 231 | 232 | # KCP is used by 233 | 234 | See [Success Stories](https://github.com/skywind3000/kcp/wiki/Success-Stories). 235 | 236 | # Donation 237 | 238 | ![欢迎使用支付宝对该项目进行捐赠](https://raw.githubusercontent.com/skywind3000/kcp/master/images/donation.png) 239 | 240 | Donation is welcome by using alipay, the money will be used to improve the protocol and documentation. 241 | 242 | 243 | twitter: https://twitter.com/skywind3000 244 | blog: http://www.skywind.me 245 | 246 | zhihu: https://www.zhihu.com/people/skywind3000 247 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | KCP - A Fast and Reliable ARQ Protocol 2 | ====================================== 3 | 4 | [![Powered][3]][1] 5 | [![GitHub license][6]][7] 6 | [![Backers on Open Collective](https://opencollective.com/kcp/backers/badge.svg)](#backers) 7 | [![Sponsors on Open Collective](https://opencollective.com/kcp/sponsors/badge.svg)](#sponsors) 8 | 9 | [1]: https://github.com/skywind3000/kcp 10 | [2]: https://github.com/skywind3000/kcp/raw/master/kcp.svg 11 | [3]: https://github.com/skywind3000/kcp/raw/master/kcp.svg 12 | [4]: https://api.travis-ci.org/skywind3000/kcp.svg?branch=master 13 | [5]: https://travis-ci.org/skywind3000/kcp 14 | [6]: https://img.shields.io/badge/license-MIT-blue.svg 15 | [7]: https://github.com/skywind3000/kcp/blob/master/LICENSE 16 | 17 | [README in English](https://github.com/skywind3000/kcp/blob/master/README.en.md) 18 | 19 | # 简介 20 | 21 | KCP是一个快速可靠协议,能以比 TCP 浪费 10%-20% 的带宽的代价,换取平均延迟降低 30%-40%,且最大延迟降低三倍的传输效果。纯算法实现,并不负责底层协议(如UDP)的收发,需要使用者自己定义下层数据包的发送方式,以 callback的方式提供给 KCP。 连时钟都需要外部传递进来,内部不会有任何一次系统调用。 22 | 23 | 整个协议只有 ikcp.h, ikcp.c两个源文件,可以方便的集成到用户自己的协议栈中。也许你实现了一个P2P,或者某个基于 UDP的协议,而缺乏一套完善的ARQ可靠协议实现,那么简单的拷贝这两个文件到现有项目中,稍微编写两行代码,即可使用。 24 | 25 | 26 | # 技术特性 27 | 28 | TCP是为流量设计的(每秒内可以传输多少KB的数据),讲究的是充分利用带宽。而 KCP是为流速设计的(单个数据包从一端发送到一端需要多少时间),以10%-20%带宽浪费的代价换取了比 TCP快30%-40%的传输速度。TCP信道是一条流速很慢,但每秒流量很大的大运河,而KCP是水流湍急的小激流。KCP有正常模式和快速模式两种,通过以下策略达到提高流速的结果: 29 | 30 | #### RTO翻倍vs不翻倍: 31 | 32 | TCP超时计算是RTOx2,这样连续丢三次包就变成RTOx8了,十分恐怖,而KCP启动快速模式后不x2,只是x1.5(实验证明1.5这个值相对比较好),提高了传输速度。 33 | 34 | #### 选择性重传 vs 全部重传: 35 | 36 | TCP丢包时会全部重传从丢的那个包开始以后的数据,KCP是选择性重传,只重传真正丢失的数据包。 37 | 38 | #### 快速重传: 39 | 40 | 发送端发送了1,2,3,4,5几个包,然后收到远端的ACK: 1, 3, 4, 5,当收到ACK3时,KCP知道2被跳过1次,收到ACK4时,知道2被跳过了2次,此时可以认为2号丢失,不用等超时,直接重传2号包,大大改善了丢包时的传输速度。 41 | 42 | #### 延迟ACK vs 非延迟ACK: 43 | 44 | TCP为了充分利用带宽,延迟发送ACK(NODELAY都没用),这样超时计算会算出较大 RTT时间,延长了丢包时的判断过程。KCP的ACK是否延迟发送可以调节。 45 | 46 | #### UNA vs ACK+UNA: 47 | 48 | ARQ模型响应有两种,UNA(此编号前所有包已收到,如TCP)和ACK(该编号包已收到),光用UNA将导致全部重传,光用ACK则丢失成本太高,以往协议都是二选其一,而 KCP协议中,除去单独的 ACK包外,所有包都有UNA信息。 49 | 50 | #### 非退让流控: 51 | 52 | KCP正常模式同TCP一样使用公平退让法则,即发送窗口大小由:发送缓存大小、接收端剩余接收缓存大小、丢包退让及慢启动这四要素决定。但传送及时性要求很高的小数据时,可选择通过配置跳过后两步,仅用前两项来控制发送频率。以牺牲部分公平性及带宽利用率之代价,换取了开着BT都能流畅传输的效果。 53 | 54 | 55 | # 快速安装 56 | 57 | 您可以使用[vcpkg](https://github.com/Microsoft/vcpkg)库管理器下载并安装kcp: 58 | 59 | git clone https://github.com/Microsoft/vcpkg.git 60 | cd vcpkg 61 | ./bootstrap-vcpkg.sh 62 | ./vcpkg integrate install 63 | ./vcpkg install kcp 64 | 65 | vcpkg中的kcp库由Microsoft团队成员和社区贡献者保持最新状态。如果版本过时,请在vcpkg存储库上[创建issue或提出PR](https://github.com/Microsoft/vcpkg)。 66 | 67 | # 基本使用 68 | 69 | 1. 创建 KCP对象: 70 | 71 | ```cpp 72 | // 初始化 kcp对象,conv为一个表示会话编号的整数,和tcp的 conv一样,通信双 73 | // 方需保证 conv相同,相互的数据包才能够被认可,user是一个给回调函数的指针 74 | ikcpcb *kcp = ikcp_create(conv, user); 75 | ``` 76 | 77 | 2. 设置回调函数: 78 | 79 | ```cpp 80 | // KCP的下层协议输出函数,KCP需要发送数据时会调用它 81 | // buf/len 表示缓存和长度 82 | // user指针为 kcp对象创建时传入的值,用于区别多个 KCP对象 83 | int udp_output(const char *buf, int len, ikcpcb *kcp, void *user) 84 | { 85 | .... 86 | } 87 | // 设置回调函数 88 | kcp->output = udp_output; 89 | ``` 90 | 91 | 3. 循环调用 update: 92 | 93 | ```cpp 94 | // 以一定频率调用 ikcp_update来更新 kcp状态,并且传入当前时钟(毫秒单位) 95 | // 如 10ms调用一次,或用 ikcp_check确定下次调用 update的时间不必每次调用 96 | ikcp_update(kcp, millisec); 97 | ``` 98 | 99 | 4. 输入一个下层数据包: 100 | 101 | ```cpp 102 | // 收到一个下层数据包(比如UDP包)时需要调用: 103 | ikcp_input(kcp, received_udp_packet, received_udp_size); 104 | ``` 105 | 处理了下层协议的输出/输入后 KCP协议就可以正常工作了,使用 ikcp_send 来向 106 | 远端发送数据。而另一端使用 ikcp_recv(kcp, ptr, size)来接收数据。 107 | 108 | 109 | # 协议配置 110 | 111 | 协议默认模式是一个标准的 ARQ,需要通过配置打开各项加速开关: 112 | 113 | 1. 工作模式: 114 | ```cpp 115 | int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc) 116 | ``` 117 | 118 | - nodelay :是否启用 nodelay模式,0不启用;1启用。 119 | - interval :协议内部工作的 interval,单位毫秒,比如 10ms或者 20ms 120 | - resend :快速重传模式,默认0关闭,可以设置2(2次ACK跨越将会直接重传) 121 | - nc :是否关闭流控,默认是0代表不关闭,1代表关闭。 122 | - 普通模式: ikcp_nodelay(kcp, 0, 40, 0, 0); 123 | - 极速模式: ikcp_nodelay(kcp, 1, 10, 2, 1); 124 | 125 | 2. 最大窗口: 126 | ```cpp 127 | int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd); 128 | ``` 129 | 该调用将会设置协议的最大发送窗口和最大接收窗口大小,默认为32. 这个可以理解为 TCP的 SND_BUF 和 RCV_BUF,只不过单位不一样 SND/RCV_BUF 单位是字节,这个单位是包。 130 | 131 | 3. 最大传输单元: 132 | 133 | 纯算法协议并不负责探测 MTU,默认 mtu是1400字节,可以使用ikcp_setmtu来设置该值。该值将会影响数据包归并及分片时候的最大传输单元。 134 | 135 | 4. 最小RTO: 136 | 137 | 不管是 TCP还是 KCP计算 RTO时都有最小 RTO的限制,即便计算出来RTO为40ms,由于默认的 RTO是100ms,协议只有在100ms后才能检测到丢包,快速模式下为30ms,可以手动更改该值: 138 | ```cpp 139 | kcp->rx_minrto = 10; 140 | ``` 141 | 142 | 143 | # 文档索引 144 | 145 | 协议的使用和配置都是很简单的,大部分情况看完上面的内容基本可以使用了。如果你需要进一步进行精细的控制,比如改变 KCP的内存分配器,或者你需要更有效的大规模调度 KCP链接(比如 3500个以上),或者如何更好的同 TCP结合,那么可以继续延伸阅读: 146 | 147 | - [Wiki Home](https://github.com/skywind3000/kcp/wiki) 148 | - [KCP 最佳实践](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice) 149 | - [同现有TCP服务器集成](https://github.com/skywind3000/kcp/wiki/Cooperate-With-Tcp-Server) 150 | - [传输数据加密](https://github.com/skywind3000/kcp/wiki/Network-Encryption) 151 | - [应用层流量控制](https://github.com/skywind3000/kcp/wiki/Flow-Control-for-Users) 152 | - [性能评测](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark) 153 | 154 | 155 | # 开源案例 156 | 157 | - [kcptun](https://github.com/xtaci/kcptun): 基于 kcp-go做的高速远程端口转发(隧道) ,配合ssh -D,可以比 shadowsocks 更流畅的看在线视频。 158 | - [dog-tunnel](https://github.com/vzex/dog-tunnel): GO开发的网络隧道,使用 KCP极大的改进了传输速度,并移植了一份 GO版本 KCP 159 | - [v2ray](https://www.v2ray.com): 著名代理软件,Shadowsocks 代替者,1.17后集成了 kcp协议,使用UDP传输,无数据包特征。 160 | - [HP-Socket](https://github.com/ldcsaa/HP-Socket): 高性能网络通信框架 HP-Socket。 161 | - [frp](https://github.com/fatedier/frp): 高性能内网穿透的反向代理软件,可将将内网服务暴露映射到外网服务器。 162 | - [asio-kcp](https://github.com/libinzhangyuan/asio_kcp): 使用 KCP的完整 UDP网络库,完整实现了基于 UDP的链接状态管理,会话控制,KCP协议调度等 163 | - [kcp-java](https://github.com/hkspirt/kcp-java): Java版本 KCP协议实现。 164 | - [kcp-netty](https://github.com/szhnet/kcp-netty): kcp的Java语言实现,基于netty。 165 | - [java-kcp](https://github.com/l42111996/java-Kcp): JAVA版本KCP,基于netty实现(包含fec功能) 166 | - [csharp-kcp](https://github.com/l42111996/csharp-kcp): csharp版本KCP,基于dotNetty实现(包含fec功能) 167 | - [kcp-cpp](https://github.com/Unit-X/kcp-cpp): KCP 的多平台(Windows、MacOS、Linux)C++ 实现作为应用程序中的简单库。包含适用于所有平台的套接字处理和辅助函数。 168 | - [kcp-perl](https://github.com/Homqyy/kcp-perl): kcp的Perl实现,其是面向对象的,Perl-Like的。 169 | - [kcp-go](https://github.com/xtaci/kcp-go): 高安全性的kcp的 GO语言实现,包含 UDP会话管理的简单实现,可以作为后续开发的基础库。 170 | - [kcp-csharp](https://github.com/limpo1989/kcp-csharp): kcp的 csharp移植,同时包含一份回话管理,可以连接上面kcp-go的服务端。 171 | - [kcp-csharp](https://github.com/KumoKyaku/KCP): 新版本 Kcp的 csharp移植。线程安全,运行时无alloc,对gc无压力。 172 | - [KcpTransport](https://github.com/Cysharp/KcpTransport): kcp的csharp移植,实现了 Syn Cookie 握手、连接管理、不可靠通信、KeepAlive,未来还将支持加密。 173 | - [Kcp-CSharp](https://github.com/Molth/Kcp-CSharp): kcp的csharp移植,非托管包装器。 174 | - [kcp2k](https://github.com/vis2k/kcp2k/): Line-by-line translation to C#, with optional Server/Client on top. 175 | - [kcp-rs](https://github.com/en/kcp-rs): KCP的 rust移植 176 | - [kcp-rust](https://github.com/Matrix-Zhang/kcp):新版本 KCP的 rust 移植 177 | - [tokio-kcp](https://github.com/Matrix-Zhang/tokio_kcp):rust tokio 的 kcp 集成 178 | - [kcp-rust-native](https://github.com/b23r0/kcp-rust-native):rust 的 kcp bindings 179 | - [lua-kcp](https://github.com/linxiaolong/lua-kcp): KCP的 Lua扩展,用于 Lua服务器 180 | - [node-kcp](https://github.com/leenjewel/node-kcp): node-js 的 KCP 接口 181 | - [nysocks](https://github.com/oyyd/nysocks): 基于libuv实现的[node-addon](https://nodejs.org/api/addons.html),提供nodejs版本的代理服务,客户端接入支持SOCKS5和ss两种协议 182 | - [shadowsocks-android](https://github.com/shadowsocks/shadowsocks-android): Shadowsocks for android 集成了 kcptun 使用 kcp协议加速 shadowsocks,效果不错 183 | - [kcpuv](https://github.com/elisaday/kcpuv): 使用 libuv开发的kcpuv库,目前还在 Demo阶段 184 | - [Lantern](https://getlantern.org/):更好的 VPN,Github 50000 星,使用 kcpgo 加速 185 | - [rpcx](https://github.com/smallnest/rpcx) :RPC 框架,1000+ 星,使用 kcpgo 加速 RPC 186 | - [xkcptun](https://github.com/liudf0716/xkcptun): c语言实现的kcptun,主要用于[OpenWrt](https://github.com/openwrt/openwrt), [LEDE](https://github.com/lede-project/source)开发的路由器项目上 187 | - [et-frame](https://github.com/egametang/ET): C#前后端框架(前端unity3d),统一用C#开发游戏,实现了前后端kcp协议 188 | - [yasio](https://github.com/yasio/yasio): 一个跨平台专注于任意客户端程序的异步socket库, 易于使用,相同的API操作KCP/TCP/UDP, 性能测试结果: [benchmark-pump](https://github.com/yasio/yasio/blob/master/benchmark.md). 189 | - [gouxp](https://github.com/shaoyuan1943/gouxp): 用Go实现基于回调方式的KCP开发包,包含加解密和FEC支持,简单易用。 190 | - [skcp](https://github.com/xboss/skcp): 基于libev实现的库,具备传输加密及基本的连接管理能力。 191 | - [pykcp](https://github.com/enkiller/pykcp): Python 版本的 KCP 实现 192 | - [php-ext-kcp](https://github.com/wpjscc/php-ext-kcp): php 的 KCP 扩展 193 | - [asio-kcp(new)](https://github.com/sniper00/asio-kcp): c++的asio/kcp支持,支持asio协程等现代c++异步模型 194 | 195 | # 商业案例 196 | 197 | - [原神](https://ys.mihoyo.com/):米哈游的《原神》使用 KCP 降低游戏消息的传输耗时,提升操作的体验。 198 | - [SpatialOS](https://improbable.io/spatialOS): 大型多人分布式游戏服务端引擎,BigWorld 的后继者,使用 KCP 加速数据传输。 199 | - [西山居](https://www.xishanju.com/):使用 KCP 进行游戏数据加速。 200 | - [CC](http://cc.163.com/):网易 CC 使用 kcp 加速视频推流,有效提高流畅性 201 | - [BOBO](http://bobo.163.com/):网易 BOBO 使用 kcp 加速主播推流 202 | - [UU](https://uu.163.com):网易 UU 加速器使用 KCP/KCPTUN 经行远程传输加速。 203 | - [阿里云](https://cn.aliyun.com/):阿里云的视频传输加速服务 GRTN 使用 KCP 进行音视频数据传输优化,动态加速产品也使用 KCP。 204 | - [云帆加速](http://www.yfcloud.com/):使用 KCP 加速文件传输和视频推流,优化了台湾主播推流的流畅度。 205 | - [明日帝国](https://www.taptap.com/app/50664):Game K17 的 《明日帝国》 (Google Play),使用 KCP 加速游戏消息,让全球玩家流畅联网 206 | - [仙灵大作战](https://www.taptap.com/app/27242):4399 的 MOBA游戏,使用 KCP 优化游戏同步 207 | 208 | 相关阅读:[《原神》也在使用 KCP 加速游戏消息](https://skywind.me/blog/archives/2706) 209 | 210 | KCP 成功的运行在多个用户规模上亿的项目上,为他们提供了更加灵敏和丝滑网络体验。 211 | 212 | 欢迎告知更多案例 213 | 214 | # 协议比较 215 | 216 | 如果网络永远不卡,那 KCP/TCP 表现类似,但是网络本身就是不可靠的,丢包和抖动无法避免(否则还要各种可靠协议干嘛)。在内网这种几乎理想的环境里直接比较,大家都差不多,但是放到公网上,放到3G/4G网络情况下,或者使用内网丢包模拟,差距就很明显了。公网在高峰期有平均接近10%的丢包,wifi/3g/4g下更糟糕,这些都会让传输变卡。 217 | 218 | 感谢 [asio-kcp](https://github.com/libinzhangyuan/asio_kcp) 的作者 [zhangyuan](https://github.com/libinzhangyuan) 对 KCP 与 enet, udt做过的一次横向评测,结论如下: 219 | 220 | - ASIO-KCP **has good performace in wifi and phone network(3G, 4G)**. 221 | - The kcp is the **first choice for realtime pvp game**. 222 | - The lag is less than 1 second when network lag happen. **3 times better than enet** when lag happen. 223 | - The enet is a good choice if your game allow 2 second lag. 224 | - **UDT is a bad idea**. It always sink into badly situation of more than serval seconds lag. And the recovery is not expected. 225 | - enet has the problem of lack of doc. And it has lots of functions that you may intrest. 226 | - kcp's doc is chinese. Good thing is the function detail which is writen in code is english. And you can use asio_kcp which is a good wrap. 227 | - The kcp is a simple thing. You will write more code if you want more feature. 228 | - UDT has a perfect doc. UDT may has more bug than others as I feeling. 229 | 230 | 具体见:[横向比较](https://github.com/libinzhangyuan/reliable_udp_bench_mark) 和 [评测数据](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark),为犹豫选择的人提供了更多指引。 231 | 232 | 大型多人游戏服务端引擎 [SpatialOS](https://improbable.io/spatialOS) 在集成 KCP 协议后做了同 TCP/RakNet 的评测: 233 | 234 | ![](https://github.com/skywind3000/kcp/raw/master/images/spatialos-50.png) 235 | 236 | 对比了在服务端刷新率为 60 Hz 同时维护 50 个角色时的响应时间,详细对比报告见: 237 | 238 | - [Kcp a new low latency secure network stack](https://improbable.io/blog/kcp-a-new-low-latency-secure-network-stack) 239 | 240 | 241 | # 关于协议 242 | 243 | 近年来,网络游戏和各类社交网络都在成几何倍数的增长,不管网络游戏还是各类互动社交网络,交互性和复杂度都在迅速提高,都需要在极短的时间内将数据同时投递给大量用户,因此传输技术自然变为未来制约发展的一个重要因素,而开源界里各种著名的传输协议,如 raknet/enet 之类,一发布都是整套协议栈一起发布,这种形式是不利于多样化的,我的项目只能选择用或者不用你,很难选择 “部分用你”,然而你一套协议栈设计的再好,是非常难以满足不同角度的各种需求的。 244 | 245 | 因此 KCP 的方式是把协议栈 “拆开”,让大家可以根据项目需求进行灵活的调整和组装,你可以下面加一层 reed solomon 的纠删码做 FEC,上面加一层类 RC4/Salsa20 做流加密,握手处再设计一套非对称密钥交换,底层 UDP 传输层再做一套动态路由系统,同时探测多条路径,选最好路径进行传输。这些不同的 “协议单元” 可以像搭建积木一般根据需要自由组合,保证 “简单性” 和 “可拆分性”,这样才能灵活适配多变的业务需求,哪个模块不好,换了就是。 246 | 247 | 未来传输方面的解决方案必然是根据使用场景深度定制的,因此给大家一个可以自由组合的 “协议单元” ,方便大家集成在自己的协议栈中。 248 | 249 | For more information, please see the [Success Stories](https://github.com/skywind3000/kcp/wiki/Success-Stories). 250 | 251 | 252 | # 关于作者 253 | 254 | 作者:林伟 (skywind3000) 255 | 256 | 欢迎关注我的:[个人博客](https://skywind.me/blog) 和 [推特](https://x.com/skywind3000)。 257 | 258 | 我在多年的开发经历中,一直都喜欢研究解决程序中的一些瓶颈问题,早年喜欢游戏开发,照着《VGA编程》来做游戏图形,读 Michael Abrash 的《图形程序开发人员指南》做软渲染器,爱好摆弄一些能够榨干 CPU 能够运行更快的代码,参加工作后,兴趣转移到服务端和网络相关的技术。 259 | 260 | 2007 年时做了几个传统游戏后开始研究快速动作游戏的同步问题,期间写过不少文章,算是国内比较早研究同步问题的人,然而发现不管怎么解决同步都需要在网络传输方面有所突破,后来离开游戏转行互联网后也发现不少领域有这方面的需求,于是开始花时间在网络传输这个领域上,尝试基于 UDP 实现一些保守的可靠协议,仿照 BSD Lite 4.4 的代码实现一些类 TCP 协议,觉得比较有意思,又接着实现一些 P2P 和动态路由网相关的玩具。KCP 协议诞生于 2011 年,基本算是自己传输方面做的几个玩具中的一个。 261 | 262 | Kcptun 的作者 xtaci 是我的大学同学,我俩都是学通信的,经常在一起研究如何进行传输优化。 263 | 264 | # 欢迎捐赠 265 | 266 | ![欢迎使用支付宝对该项目进行捐赠](images/donation.png) 267 | 268 | 欢迎使用支付宝手扫描上面的二维码,对该项目进行捐赠。捐赠款项将用于持续优化 KCP协议以及完善文档。 269 | 270 | 感谢:明明、星仔、进、帆、颁钊、斌铨、晓丹、余争、虎、晟敢、徐玮、王川、赵刚强、胡知锋、万新朝、何新超、刘旸、侯宪辉、吴佩仪、华斌、如涛、胡坚。。。(早先的名单实在不好意思没记录下来)等同学的捐助与支持。 271 | 272 | 273 | 欢迎关注 274 | 275 | KCP交流群:364933586(QQ群号),KCP集成,调优,网络传输以及相关技术讨论 276 | 277 | Gitter 群:https://gitter.im/skywind3000/KCP 278 | 279 | blog: http://www.skywind.me 280 | 281 | 282 | 283 | ## Contributors 284 | 285 | This project exists thanks to all the people who contribute. 286 | 287 | 288 | -------------------------------------------------------------------------------- /benchmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skywind3000/kcp/f4f3a89cc632647dabdcb146932d2afd5591e62e/benchmark.png -------------------------------------------------------------------------------- /ikcp.c: -------------------------------------------------------------------------------- 1 | //===================================================================== 2 | // 3 | // KCP - A Better ARQ Protocol Implementation 4 | // skywind3000 (at) gmail.com, 2010-2011 5 | // 6 | // Features: 7 | // + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. 8 | // + Maximum RTT reduce three times vs tcp. 9 | // + Lightweight, distributed as a single source file. 10 | // 11 | //===================================================================== 12 | #include "ikcp.h" 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #define IKCP_FASTACK_CONSERVE 21 | 22 | //===================================================================== 23 | // KCP BASIC 24 | //===================================================================== 25 | const IUINT32 IKCP_RTO_NDL = 30; // no delay min rto 26 | const IUINT32 IKCP_RTO_MIN = 100; // normal min rto 27 | const IUINT32 IKCP_RTO_DEF = 200; 28 | const IUINT32 IKCP_RTO_MAX = 60000; 29 | const IUINT32 IKCP_CMD_PUSH = 81; // cmd: push data 30 | const IUINT32 IKCP_CMD_ACK = 82; // cmd: ack 31 | const IUINT32 IKCP_CMD_WASK = 83; // cmd: window probe (ask) 32 | const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell) 33 | const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK 34 | const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS 35 | const IUINT32 IKCP_WND_SND = 32; 36 | const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size 37 | const IUINT32 IKCP_MTU_DEF = 1400; 38 | const IUINT32 IKCP_ACK_FAST = 3; 39 | const IUINT32 IKCP_INTERVAL = 100; 40 | const IUINT32 IKCP_OVERHEAD = 24; 41 | const IUINT32 IKCP_DEADLINK = 20; 42 | const IUINT32 IKCP_THRESH_INIT = 2; 43 | const IUINT32 IKCP_THRESH_MIN = 2; 44 | const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size 45 | const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window 46 | const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack 47 | 48 | 49 | //--------------------------------------------------------------------- 50 | // encode / decode 51 | //--------------------------------------------------------------------- 52 | 53 | /* encode 8 bits unsigned int */ 54 | static inline char *ikcp_encode8u(char *p, unsigned char c) 55 | { 56 | *(unsigned char*)p++ = c; 57 | return p; 58 | } 59 | 60 | /* decode 8 bits unsigned int */ 61 | static inline const char *ikcp_decode8u(const char *p, unsigned char *c) 62 | { 63 | *c = *(unsigned char*)p++; 64 | return p; 65 | } 66 | 67 | /* encode 16 bits unsigned int (lsb) */ 68 | static inline char *ikcp_encode16u(char *p, unsigned short w) 69 | { 70 | #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN 71 | *(unsigned char*)(p + 0) = (w & 255); 72 | *(unsigned char*)(p + 1) = (w >> 8); 73 | #else 74 | memcpy(p, &w, 2); 75 | #endif 76 | p += 2; 77 | return p; 78 | } 79 | 80 | /* decode 16 bits unsigned int (lsb) */ 81 | static inline const char *ikcp_decode16u(const char *p, unsigned short *w) 82 | { 83 | #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN 84 | *w = *(const unsigned char*)(p + 1); 85 | *w = *(const unsigned char*)(p + 0) + (*w << 8); 86 | #else 87 | memcpy(w, p, 2); 88 | #endif 89 | p += 2; 90 | return p; 91 | } 92 | 93 | /* encode 32 bits unsigned int (lsb) */ 94 | static inline char *ikcp_encode32u(char *p, IUINT32 l) 95 | { 96 | #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN 97 | *(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff); 98 | *(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff); 99 | *(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff); 100 | *(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff); 101 | #else 102 | memcpy(p, &l, 4); 103 | #endif 104 | p += 4; 105 | return p; 106 | } 107 | 108 | /* decode 32 bits unsigned int (lsb) */ 109 | static inline const char *ikcp_decode32u(const char *p, IUINT32 *l) 110 | { 111 | #if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN 112 | *l = *(const unsigned char*)(p + 3); 113 | *l = *(const unsigned char*)(p + 2) + (*l << 8); 114 | *l = *(const unsigned char*)(p + 1) + (*l << 8); 115 | *l = *(const unsigned char*)(p + 0) + (*l << 8); 116 | #else 117 | memcpy(l, p, 4); 118 | #endif 119 | p += 4; 120 | return p; 121 | } 122 | 123 | static inline IUINT32 _imin_(IUINT32 a, IUINT32 b) { 124 | return a <= b ? a : b; 125 | } 126 | 127 | static inline IUINT32 _imax_(IUINT32 a, IUINT32 b) { 128 | return a >= b ? a : b; 129 | } 130 | 131 | static inline IUINT32 _ibound_(IUINT32 lower, IUINT32 middle, IUINT32 upper) 132 | { 133 | return _imin_(_imax_(lower, middle), upper); 134 | } 135 | 136 | static inline long _itimediff(IUINT32 later, IUINT32 earlier) 137 | { 138 | return ((IINT32)(later - earlier)); 139 | } 140 | 141 | //--------------------------------------------------------------------- 142 | // manage segment 143 | //--------------------------------------------------------------------- 144 | typedef struct IKCPSEG IKCPSEG; 145 | 146 | static void* (*ikcp_malloc_hook)(size_t) = NULL; 147 | static void (*ikcp_free_hook)(void *) = NULL; 148 | 149 | // internal malloc 150 | static void* ikcp_malloc(size_t size) { 151 | if (ikcp_malloc_hook) 152 | return ikcp_malloc_hook(size); 153 | return malloc(size); 154 | } 155 | 156 | // internal free 157 | static void ikcp_free(void *ptr) { 158 | if (ikcp_free_hook) { 159 | ikcp_free_hook(ptr); 160 | } else { 161 | free(ptr); 162 | } 163 | } 164 | 165 | // redefine allocator 166 | void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)) 167 | { 168 | ikcp_malloc_hook = new_malloc; 169 | ikcp_free_hook = new_free; 170 | } 171 | 172 | // allocate a new kcp segment 173 | static IKCPSEG* ikcp_segment_new(ikcpcb *kcp, int size) 174 | { 175 | return (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size); 176 | } 177 | 178 | // delete a segment 179 | static void ikcp_segment_delete(ikcpcb *kcp, IKCPSEG *seg) 180 | { 181 | ikcp_free(seg); 182 | } 183 | 184 | // write log 185 | void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...) 186 | { 187 | char buffer[1024]; 188 | va_list argptr; 189 | if ((mask & kcp->logmask) == 0 || kcp->writelog == 0) return; 190 | va_start(argptr, fmt); 191 | vsprintf(buffer, fmt, argptr); 192 | va_end(argptr); 193 | kcp->writelog(buffer, kcp, kcp->user); 194 | } 195 | 196 | // check log mask 197 | static int ikcp_canlog(const ikcpcb *kcp, int mask) 198 | { 199 | if ((mask & kcp->logmask) == 0 || kcp->writelog == NULL) return 0; 200 | return 1; 201 | } 202 | 203 | // output segment 204 | static int ikcp_output(ikcpcb *kcp, const void *data, int size) 205 | { 206 | assert(kcp); 207 | assert(kcp->output); 208 | if (ikcp_canlog(kcp, IKCP_LOG_OUTPUT)) { 209 | ikcp_log(kcp, IKCP_LOG_OUTPUT, "[RO] %ld bytes", (long)size); 210 | } 211 | if (size == 0) return 0; 212 | return kcp->output((const char*)data, size, kcp, kcp->user); 213 | } 214 | 215 | // output queue 216 | void ikcp_qprint(const char *name, const struct IQUEUEHEAD *head) 217 | { 218 | #if 0 219 | const struct IQUEUEHEAD *p; 220 | printf("<%s>: [", name); 221 | for (p = head->next; p != head; p = p->next) { 222 | const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); 223 | printf("(%lu %d)", (unsigned long)seg->sn, (int)(seg->ts % 10000)); 224 | if (p->next != head) printf(","); 225 | } 226 | printf("]\n"); 227 | #endif 228 | } 229 | 230 | 231 | //--------------------------------------------------------------------- 232 | // create a new kcpcb 233 | //--------------------------------------------------------------------- 234 | ikcpcb* ikcp_create(IUINT32 conv, void *user) 235 | { 236 | ikcpcb *kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB)); 237 | if (kcp == NULL) return NULL; 238 | kcp->conv = conv; 239 | kcp->user = user; 240 | kcp->snd_una = 0; 241 | kcp->snd_nxt = 0; 242 | kcp->rcv_nxt = 0; 243 | kcp->ts_recent = 0; 244 | kcp->ts_lastack = 0; 245 | kcp->ts_probe = 0; 246 | kcp->probe_wait = 0; 247 | kcp->snd_wnd = IKCP_WND_SND; 248 | kcp->rcv_wnd = IKCP_WND_RCV; 249 | kcp->rmt_wnd = IKCP_WND_RCV; 250 | kcp->cwnd = 0; 251 | kcp->incr = 0; 252 | kcp->probe = 0; 253 | kcp->mtu = IKCP_MTU_DEF; 254 | kcp->mss = kcp->mtu - IKCP_OVERHEAD; 255 | kcp->stream = 0; 256 | 257 | kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3); 258 | if (kcp->buffer == NULL) { 259 | ikcp_free(kcp); 260 | return NULL; 261 | } 262 | 263 | iqueue_init(&kcp->snd_queue); 264 | iqueue_init(&kcp->rcv_queue); 265 | iqueue_init(&kcp->snd_buf); 266 | iqueue_init(&kcp->rcv_buf); 267 | kcp->nrcv_buf = 0; 268 | kcp->nsnd_buf = 0; 269 | kcp->nrcv_que = 0; 270 | kcp->nsnd_que = 0; 271 | kcp->state = 0; 272 | kcp->acklist = NULL; 273 | kcp->ackblock = 0; 274 | kcp->ackcount = 0; 275 | kcp->rx_srtt = 0; 276 | kcp->rx_rttval = 0; 277 | kcp->rx_rto = IKCP_RTO_DEF; 278 | kcp->rx_minrto = IKCP_RTO_MIN; 279 | kcp->current = 0; 280 | kcp->interval = IKCP_INTERVAL; 281 | kcp->ts_flush = IKCP_INTERVAL; 282 | kcp->nodelay = 0; 283 | kcp->updated = 0; 284 | kcp->logmask = 0; 285 | kcp->ssthresh = IKCP_THRESH_INIT; 286 | kcp->fastresend = 0; 287 | kcp->fastlimit = IKCP_FASTACK_LIMIT; 288 | kcp->nocwnd = 0; 289 | kcp->xmit = 0; 290 | kcp->dead_link = IKCP_DEADLINK; 291 | kcp->output = NULL; 292 | kcp->writelog = NULL; 293 | 294 | return kcp; 295 | } 296 | 297 | 298 | //--------------------------------------------------------------------- 299 | // release a new kcpcb 300 | //--------------------------------------------------------------------- 301 | void ikcp_release(ikcpcb *kcp) 302 | { 303 | assert(kcp); 304 | if (kcp) { 305 | IKCPSEG *seg; 306 | while (!iqueue_is_empty(&kcp->snd_buf)) { 307 | seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node); 308 | iqueue_del(&seg->node); 309 | ikcp_segment_delete(kcp, seg); 310 | } 311 | while (!iqueue_is_empty(&kcp->rcv_buf)) { 312 | seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); 313 | iqueue_del(&seg->node); 314 | ikcp_segment_delete(kcp, seg); 315 | } 316 | while (!iqueue_is_empty(&kcp->snd_queue)) { 317 | seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); 318 | iqueue_del(&seg->node); 319 | ikcp_segment_delete(kcp, seg); 320 | } 321 | while (!iqueue_is_empty(&kcp->rcv_queue)) { 322 | seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); 323 | iqueue_del(&seg->node); 324 | ikcp_segment_delete(kcp, seg); 325 | } 326 | if (kcp->buffer) { 327 | ikcp_free(kcp->buffer); 328 | } 329 | if (kcp->acklist) { 330 | ikcp_free(kcp->acklist); 331 | } 332 | 333 | kcp->nrcv_buf = 0; 334 | kcp->nsnd_buf = 0; 335 | kcp->nrcv_que = 0; 336 | kcp->nsnd_que = 0; 337 | kcp->ackcount = 0; 338 | kcp->buffer = NULL; 339 | kcp->acklist = NULL; 340 | ikcp_free(kcp); 341 | } 342 | } 343 | 344 | 345 | //--------------------------------------------------------------------- 346 | // set output callback, which will be invoked by kcp 347 | //--------------------------------------------------------------------- 348 | void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, 349 | ikcpcb *kcp, void *user)) 350 | { 351 | kcp->output = output; 352 | } 353 | 354 | 355 | //--------------------------------------------------------------------- 356 | // user/upper level recv: returns size, returns below zero for EAGAIN 357 | //--------------------------------------------------------------------- 358 | int ikcp_recv(ikcpcb *kcp, char *buffer, int len) 359 | { 360 | struct IQUEUEHEAD *p; 361 | int ispeek = (len < 0)? 1 : 0; 362 | int peeksize; 363 | int recover = 0; 364 | IKCPSEG *seg; 365 | assert(kcp); 366 | 367 | if (iqueue_is_empty(&kcp->rcv_queue)) 368 | return -1; 369 | 370 | if (len < 0) len = -len; 371 | 372 | peeksize = ikcp_peeksize(kcp); 373 | 374 | if (peeksize < 0) 375 | return -2; 376 | 377 | if (peeksize > len) 378 | return -3; 379 | 380 | if (kcp->nrcv_que >= kcp->rcv_wnd) 381 | recover = 1; 382 | 383 | // merge fragment 384 | for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue; ) { 385 | int fragment; 386 | seg = iqueue_entry(p, IKCPSEG, node); 387 | p = p->next; 388 | 389 | if (buffer) { 390 | memcpy(buffer, seg->data, seg->len); 391 | buffer += seg->len; 392 | } 393 | 394 | len += seg->len; 395 | fragment = seg->frg; 396 | 397 | if (ikcp_canlog(kcp, IKCP_LOG_RECV)) { 398 | ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn); 399 | } 400 | 401 | if (ispeek == 0) { 402 | iqueue_del(&seg->node); 403 | ikcp_segment_delete(kcp, seg); 404 | kcp->nrcv_que--; 405 | } 406 | 407 | if (fragment == 0) 408 | break; 409 | } 410 | 411 | assert(len == peeksize); 412 | 413 | // move available data from rcv_buf -> rcv_queue 414 | while (! iqueue_is_empty(&kcp->rcv_buf)) { 415 | seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); 416 | if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { 417 | iqueue_del(&seg->node); 418 | kcp->nrcv_buf--; 419 | iqueue_add_tail(&seg->node, &kcp->rcv_queue); 420 | kcp->nrcv_que++; 421 | kcp->rcv_nxt++; 422 | } else { 423 | break; 424 | } 425 | } 426 | 427 | // fast recover 428 | if (kcp->nrcv_que < kcp->rcv_wnd && recover) { 429 | // ready to send back IKCP_CMD_WINS in ikcp_flush 430 | // tell remote my window size 431 | kcp->probe |= IKCP_ASK_TELL; 432 | } 433 | 434 | return len; 435 | } 436 | 437 | 438 | //--------------------------------------------------------------------- 439 | // peek data size 440 | //--------------------------------------------------------------------- 441 | int ikcp_peeksize(const ikcpcb *kcp) 442 | { 443 | struct IQUEUEHEAD *p; 444 | IKCPSEG *seg; 445 | int length = 0; 446 | 447 | assert(kcp); 448 | 449 | if (iqueue_is_empty(&kcp->rcv_queue)) return -1; 450 | 451 | seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); 452 | if (seg->frg == 0) return seg->len; 453 | 454 | if (kcp->nrcv_que < seg->frg + 1) return -1; 455 | 456 | for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) { 457 | seg = iqueue_entry(p, IKCPSEG, node); 458 | length += seg->len; 459 | if (seg->frg == 0) break; 460 | } 461 | 462 | return length; 463 | } 464 | 465 | 466 | //--------------------------------------------------------------------- 467 | // user/upper level send, returns below zero for error 468 | //--------------------------------------------------------------------- 469 | int ikcp_send(ikcpcb *kcp, const char *buffer, int len) 470 | { 471 | IKCPSEG *seg; 472 | int count, i; 473 | int sent = 0; 474 | 475 | assert(kcp->mss > 0); 476 | if (len < 0) return -1; 477 | 478 | // append to previous segment in streaming mode (if possible) 479 | if (kcp->stream != 0) { 480 | if (!iqueue_is_empty(&kcp->snd_queue)) { 481 | IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node); 482 | if (old->len < kcp->mss) { 483 | int capacity = kcp->mss - old->len; 484 | int extend = (len < capacity)? len : capacity; 485 | seg = ikcp_segment_new(kcp, old->len + extend); 486 | assert(seg); 487 | if (seg == NULL) { 488 | return -2; 489 | } 490 | iqueue_add_tail(&seg->node, &kcp->snd_queue); 491 | memcpy(seg->data, old->data, old->len); 492 | if (buffer) { 493 | memcpy(seg->data + old->len, buffer, extend); 494 | buffer += extend; 495 | } 496 | seg->len = old->len + extend; 497 | seg->frg = 0; 498 | len -= extend; 499 | iqueue_del_init(&old->node); 500 | ikcp_segment_delete(kcp, old); 501 | sent = extend; 502 | } 503 | } 504 | if (len <= 0) { 505 | return sent; 506 | } 507 | } 508 | 509 | if (len <= (int)kcp->mss) count = 1; 510 | else count = (len + kcp->mss - 1) / kcp->mss; 511 | 512 | if (count >= (int)IKCP_WND_RCV) { 513 | if (kcp->stream != 0 && sent > 0) 514 | return sent; 515 | return -2; 516 | } 517 | 518 | if (count == 0) count = 1; 519 | 520 | // fragment 521 | for (i = 0; i < count; i++) { 522 | int size = len > (int)kcp->mss ? (int)kcp->mss : len; 523 | seg = ikcp_segment_new(kcp, size); 524 | assert(seg); 525 | if (seg == NULL) { 526 | return -2; 527 | } 528 | if (buffer && len > 0) { 529 | memcpy(seg->data, buffer, size); 530 | } 531 | seg->len = size; 532 | seg->frg = (kcp->stream == 0)? (count - i - 1) : 0; 533 | iqueue_init(&seg->node); 534 | iqueue_add_tail(&seg->node, &kcp->snd_queue); 535 | kcp->nsnd_que++; 536 | if (buffer) { 537 | buffer += size; 538 | } 539 | len -= size; 540 | sent += size; 541 | } 542 | 543 | return sent; 544 | } 545 | 546 | 547 | //--------------------------------------------------------------------- 548 | // parse ack 549 | //--------------------------------------------------------------------- 550 | static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt) 551 | { 552 | IINT32 rto = 0; 553 | if (kcp->rx_srtt == 0) { 554 | kcp->rx_srtt = rtt; 555 | kcp->rx_rttval = rtt / 2; 556 | } else { 557 | long delta = rtt - kcp->rx_srtt; 558 | if (delta < 0) delta = -delta; 559 | kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4; 560 | kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8; 561 | if (kcp->rx_srtt < 1) kcp->rx_srtt = 1; 562 | } 563 | rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval); 564 | kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX); 565 | } 566 | 567 | static void ikcp_shrink_buf(ikcpcb *kcp) 568 | { 569 | struct IQUEUEHEAD *p = kcp->snd_buf.next; 570 | if (p != &kcp->snd_buf) { 571 | IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); 572 | kcp->snd_una = seg->sn; 573 | } else { 574 | kcp->snd_una = kcp->snd_nxt; 575 | } 576 | } 577 | 578 | static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn) 579 | { 580 | struct IQUEUEHEAD *p, *next; 581 | 582 | if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) 583 | return; 584 | 585 | for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { 586 | IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); 587 | next = p->next; 588 | if (sn == seg->sn) { 589 | iqueue_del(p); 590 | ikcp_segment_delete(kcp, seg); 591 | kcp->nsnd_buf--; 592 | break; 593 | } 594 | if (_itimediff(sn, seg->sn) < 0) { 595 | break; 596 | } 597 | } 598 | } 599 | 600 | static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una) 601 | { 602 | struct IQUEUEHEAD *p, *next; 603 | for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { 604 | IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); 605 | next = p->next; 606 | if (_itimediff(una, seg->sn) > 0) { 607 | iqueue_del(p); 608 | ikcp_segment_delete(kcp, seg); 609 | kcp->nsnd_buf--; 610 | } else { 611 | break; 612 | } 613 | } 614 | } 615 | 616 | static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) 617 | { 618 | struct IQUEUEHEAD *p, *next; 619 | 620 | if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) 621 | return; 622 | 623 | for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { 624 | IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); 625 | next = p->next; 626 | if (_itimediff(sn, seg->sn) < 0) { 627 | break; 628 | } 629 | else if (sn != seg->sn) { 630 | #ifndef IKCP_FASTACK_CONSERVE 631 | seg->fastack++; 632 | #else 633 | if (_itimediff(ts, seg->ts) >= 0) 634 | seg->fastack++; 635 | #endif 636 | } 637 | } 638 | } 639 | 640 | 641 | //--------------------------------------------------------------------- 642 | // ack append 643 | //--------------------------------------------------------------------- 644 | static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) 645 | { 646 | IUINT32 newsize = kcp->ackcount + 1; 647 | IUINT32 *ptr; 648 | 649 | if (newsize > kcp->ackblock) { 650 | IUINT32 *acklist; 651 | IUINT32 newblock; 652 | 653 | for (newblock = 8; newblock < newsize; newblock <<= 1); 654 | acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2); 655 | 656 | if (acklist == NULL) { 657 | assert(acklist != NULL); 658 | abort(); 659 | } 660 | 661 | if (kcp->acklist != NULL) { 662 | IUINT32 x; 663 | for (x = 0; x < kcp->ackcount; x++) { 664 | acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0]; 665 | acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1]; 666 | } 667 | ikcp_free(kcp->acklist); 668 | } 669 | 670 | kcp->acklist = acklist; 671 | kcp->ackblock = newblock; 672 | } 673 | 674 | ptr = &kcp->acklist[kcp->ackcount * 2]; 675 | ptr[0] = sn; 676 | ptr[1] = ts; 677 | kcp->ackcount++; 678 | } 679 | 680 | static void ikcp_ack_get(const ikcpcb *kcp, int p, IUINT32 *sn, IUINT32 *ts) 681 | { 682 | if (sn) sn[0] = kcp->acklist[p * 2 + 0]; 683 | if (ts) ts[0] = kcp->acklist[p * 2 + 1]; 684 | } 685 | 686 | 687 | //--------------------------------------------------------------------- 688 | // parse data 689 | //--------------------------------------------------------------------- 690 | void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg) 691 | { 692 | struct IQUEUEHEAD *p, *prev; 693 | IUINT32 sn = newseg->sn; 694 | int repeat = 0; 695 | 696 | if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 || 697 | _itimediff(sn, kcp->rcv_nxt) < 0) { 698 | ikcp_segment_delete(kcp, newseg); 699 | return; 700 | } 701 | 702 | for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) { 703 | IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); 704 | prev = p->prev; 705 | if (seg->sn == sn) { 706 | repeat = 1; 707 | break; 708 | } 709 | if (_itimediff(sn, seg->sn) > 0) { 710 | break; 711 | } 712 | } 713 | 714 | if (repeat == 0) { 715 | iqueue_init(&newseg->node); 716 | iqueue_add(&newseg->node, p); 717 | kcp->nrcv_buf++; 718 | } else { 719 | ikcp_segment_delete(kcp, newseg); 720 | } 721 | 722 | #if 0 723 | ikcp_qprint("rcvbuf", &kcp->rcv_buf); 724 | printf("rcv_nxt=%lu\n", kcp->rcv_nxt); 725 | #endif 726 | 727 | // move available data from rcv_buf -> rcv_queue 728 | while (! iqueue_is_empty(&kcp->rcv_buf)) { 729 | IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); 730 | if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { 731 | iqueue_del(&seg->node); 732 | kcp->nrcv_buf--; 733 | iqueue_add_tail(&seg->node, &kcp->rcv_queue); 734 | kcp->nrcv_que++; 735 | kcp->rcv_nxt++; 736 | } else { 737 | break; 738 | } 739 | } 740 | 741 | #if 0 742 | ikcp_qprint("queue", &kcp->rcv_queue); 743 | printf("rcv_nxt=%lu\n", kcp->rcv_nxt); 744 | #endif 745 | 746 | #if 1 747 | // printf("snd(buf=%d, queue=%d)\n", kcp->nsnd_buf, kcp->nsnd_que); 748 | // printf("rcv(buf=%d, queue=%d)\n", kcp->nrcv_buf, kcp->nrcv_que); 749 | #endif 750 | } 751 | 752 | 753 | //--------------------------------------------------------------------- 754 | // input data 755 | //--------------------------------------------------------------------- 756 | int ikcp_input(ikcpcb *kcp, const char *data, long size) 757 | { 758 | IUINT32 prev_una = kcp->snd_una; 759 | IUINT32 maxack = 0, latest_ts = 0; 760 | int flag = 0; 761 | 762 | if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) { 763 | ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size); 764 | } 765 | 766 | if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1; 767 | 768 | while (1) { 769 | IUINT32 ts, sn, len, una, conv; 770 | IUINT16 wnd; 771 | IUINT8 cmd, frg; 772 | IKCPSEG *seg; 773 | 774 | if (size < (int)IKCP_OVERHEAD) break; 775 | 776 | data = ikcp_decode32u(data, &conv); 777 | if (conv != kcp->conv) return -1; 778 | 779 | data = ikcp_decode8u(data, &cmd); 780 | data = ikcp_decode8u(data, &frg); 781 | data = ikcp_decode16u(data, &wnd); 782 | data = ikcp_decode32u(data, &ts); 783 | data = ikcp_decode32u(data, &sn); 784 | data = ikcp_decode32u(data, &una); 785 | data = ikcp_decode32u(data, &len); 786 | 787 | size -= IKCP_OVERHEAD; 788 | 789 | if ((long)size < (long)len || (int)len < 0) return -2; 790 | 791 | if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK && 792 | cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS) 793 | return -3; 794 | 795 | kcp->rmt_wnd = wnd; 796 | ikcp_parse_una(kcp, una); 797 | ikcp_shrink_buf(kcp); 798 | 799 | if (cmd == IKCP_CMD_ACK) { 800 | if (_itimediff(kcp->current, ts) >= 0) { 801 | ikcp_update_ack(kcp, _itimediff(kcp->current, ts)); 802 | } 803 | ikcp_parse_ack(kcp, sn); 804 | ikcp_shrink_buf(kcp); 805 | if (flag == 0) { 806 | flag = 1; 807 | maxack = sn; 808 | latest_ts = ts; 809 | } else { 810 | if (_itimediff(sn, maxack) > 0) { 811 | #ifndef IKCP_FASTACK_CONSERVE 812 | maxack = sn; 813 | latest_ts = ts; 814 | #else 815 | if (_itimediff(ts, latest_ts) > 0) { 816 | maxack = sn; 817 | latest_ts = ts; 818 | } 819 | #endif 820 | } 821 | } 822 | if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) { 823 | ikcp_log(kcp, IKCP_LOG_IN_ACK, 824 | "input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn, 825 | (long)_itimediff(kcp->current, ts), 826 | (long)kcp->rx_rto); 827 | } 828 | } 829 | else if (cmd == IKCP_CMD_PUSH) { 830 | if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) { 831 | ikcp_log(kcp, IKCP_LOG_IN_DATA, 832 | "input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts); 833 | } 834 | if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) { 835 | ikcp_ack_push(kcp, sn, ts); 836 | if (_itimediff(sn, kcp->rcv_nxt) >= 0) { 837 | seg = ikcp_segment_new(kcp, len); 838 | seg->conv = conv; 839 | seg->cmd = cmd; 840 | seg->frg = frg; 841 | seg->wnd = wnd; 842 | seg->ts = ts; 843 | seg->sn = sn; 844 | seg->una = una; 845 | seg->len = len; 846 | 847 | if (len > 0) { 848 | memcpy(seg->data, data, len); 849 | } 850 | 851 | ikcp_parse_data(kcp, seg); 852 | } 853 | } 854 | } 855 | else if (cmd == IKCP_CMD_WASK) { 856 | // ready to send back IKCP_CMD_WINS in ikcp_flush 857 | // tell remote my window size 858 | kcp->probe |= IKCP_ASK_TELL; 859 | if (ikcp_canlog(kcp, IKCP_LOG_IN_PROBE)) { 860 | ikcp_log(kcp, IKCP_LOG_IN_PROBE, "input probe"); 861 | } 862 | } 863 | else if (cmd == IKCP_CMD_WINS) { 864 | // do nothing 865 | if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) { 866 | ikcp_log(kcp, IKCP_LOG_IN_WINS, 867 | "input wins: %lu", (unsigned long)(wnd)); 868 | } 869 | } 870 | else { 871 | return -3; 872 | } 873 | 874 | data += len; 875 | size -= len; 876 | } 877 | 878 | if (flag != 0) { 879 | ikcp_parse_fastack(kcp, maxack, latest_ts); 880 | } 881 | 882 | if (_itimediff(kcp->snd_una, prev_una) > 0) { 883 | if (kcp->cwnd < kcp->rmt_wnd) { 884 | IUINT32 mss = kcp->mss; 885 | if (kcp->cwnd < kcp->ssthresh) { 886 | kcp->cwnd++; 887 | kcp->incr += mss; 888 | } else { 889 | if (kcp->incr < mss) kcp->incr = mss; 890 | kcp->incr += (mss * mss) / kcp->incr + (mss / 16); 891 | if ((kcp->cwnd + 1) * mss <= kcp->incr) { 892 | #if 1 893 | kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1); 894 | #else 895 | kcp->cwnd++; 896 | #endif 897 | } 898 | } 899 | if (kcp->cwnd > kcp->rmt_wnd) { 900 | kcp->cwnd = kcp->rmt_wnd; 901 | kcp->incr = kcp->rmt_wnd * mss; 902 | } 903 | } 904 | } 905 | 906 | return 0; 907 | } 908 | 909 | 910 | //--------------------------------------------------------------------- 911 | // ikcp_encode_seg 912 | //--------------------------------------------------------------------- 913 | static char *ikcp_encode_seg(char *ptr, const IKCPSEG *seg) 914 | { 915 | ptr = ikcp_encode32u(ptr, seg->conv); 916 | ptr = ikcp_encode8u(ptr, (IUINT8)seg->cmd); 917 | ptr = ikcp_encode8u(ptr, (IUINT8)seg->frg); 918 | ptr = ikcp_encode16u(ptr, (IUINT16)seg->wnd); 919 | ptr = ikcp_encode32u(ptr, seg->ts); 920 | ptr = ikcp_encode32u(ptr, seg->sn); 921 | ptr = ikcp_encode32u(ptr, seg->una); 922 | ptr = ikcp_encode32u(ptr, seg->len); 923 | return ptr; 924 | } 925 | 926 | static int ikcp_wnd_unused(const ikcpcb *kcp) 927 | { 928 | if (kcp->nrcv_que < kcp->rcv_wnd) { 929 | return kcp->rcv_wnd - kcp->nrcv_que; 930 | } 931 | return 0; 932 | } 933 | 934 | 935 | //--------------------------------------------------------------------- 936 | // ikcp_flush 937 | //--------------------------------------------------------------------- 938 | void ikcp_flush(ikcpcb *kcp) 939 | { 940 | IUINT32 current = kcp->current; 941 | char *buffer = kcp->buffer; 942 | char *ptr = buffer; 943 | int count, size, i; 944 | IUINT32 resent, cwnd; 945 | IUINT32 rtomin; 946 | struct IQUEUEHEAD *p; 947 | int change = 0; 948 | int lost = 0; 949 | IKCPSEG seg; 950 | 951 | // 'ikcp_update' haven't been called. 952 | if (kcp->updated == 0) return; 953 | 954 | seg.conv = kcp->conv; 955 | seg.cmd = IKCP_CMD_ACK; 956 | seg.frg = 0; 957 | seg.wnd = ikcp_wnd_unused(kcp); 958 | seg.una = kcp->rcv_nxt; 959 | seg.len = 0; 960 | seg.sn = 0; 961 | seg.ts = 0; 962 | 963 | // flush acknowledges 964 | count = kcp->ackcount; 965 | for (i = 0; i < count; i++) { 966 | size = (int)(ptr - buffer); 967 | if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { 968 | ikcp_output(kcp, buffer, size); 969 | ptr = buffer; 970 | } 971 | ikcp_ack_get(kcp, i, &seg.sn, &seg.ts); 972 | ptr = ikcp_encode_seg(ptr, &seg); 973 | } 974 | 975 | kcp->ackcount = 0; 976 | 977 | // probe window size (if remote window size equals zero) 978 | if (kcp->rmt_wnd == 0) { 979 | if (kcp->probe_wait == 0) { 980 | kcp->probe_wait = IKCP_PROBE_INIT; 981 | kcp->ts_probe = kcp->current + kcp->probe_wait; 982 | } 983 | else { 984 | if (_itimediff(kcp->current, kcp->ts_probe) >= 0) { 985 | if (kcp->probe_wait < IKCP_PROBE_INIT) 986 | kcp->probe_wait = IKCP_PROBE_INIT; 987 | kcp->probe_wait += kcp->probe_wait / 2; 988 | if (kcp->probe_wait > IKCP_PROBE_LIMIT) 989 | kcp->probe_wait = IKCP_PROBE_LIMIT; 990 | kcp->ts_probe = kcp->current + kcp->probe_wait; 991 | kcp->probe |= IKCP_ASK_SEND; 992 | } 993 | } 994 | } else { 995 | kcp->ts_probe = 0; 996 | kcp->probe_wait = 0; 997 | } 998 | 999 | // flush window probing commands 1000 | if (kcp->probe & IKCP_ASK_SEND) { 1001 | seg.cmd = IKCP_CMD_WASK; 1002 | size = (int)(ptr - buffer); 1003 | if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { 1004 | ikcp_output(kcp, buffer, size); 1005 | ptr = buffer; 1006 | } 1007 | ptr = ikcp_encode_seg(ptr, &seg); 1008 | } 1009 | 1010 | // flush window probing commands 1011 | if (kcp->probe & IKCP_ASK_TELL) { 1012 | seg.cmd = IKCP_CMD_WINS; 1013 | size = (int)(ptr - buffer); 1014 | if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { 1015 | ikcp_output(kcp, buffer, size); 1016 | ptr = buffer; 1017 | } 1018 | ptr = ikcp_encode_seg(ptr, &seg); 1019 | } 1020 | 1021 | kcp->probe = 0; 1022 | 1023 | // calculate window size 1024 | cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd); 1025 | if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd); 1026 | 1027 | // move data from snd_queue to snd_buf 1028 | while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) { 1029 | IKCPSEG *newseg; 1030 | if (iqueue_is_empty(&kcp->snd_queue)) break; 1031 | 1032 | newseg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); 1033 | 1034 | iqueue_del(&newseg->node); 1035 | iqueue_add_tail(&newseg->node, &kcp->snd_buf); 1036 | kcp->nsnd_que--; 1037 | kcp->nsnd_buf++; 1038 | 1039 | newseg->conv = kcp->conv; 1040 | newseg->cmd = IKCP_CMD_PUSH; 1041 | newseg->wnd = seg.wnd; 1042 | newseg->ts = current; 1043 | newseg->sn = kcp->snd_nxt++; 1044 | newseg->una = kcp->rcv_nxt; 1045 | newseg->resendts = current; 1046 | newseg->rto = kcp->rx_rto; 1047 | newseg->fastack = 0; 1048 | newseg->xmit = 0; 1049 | } 1050 | 1051 | // calculate resent 1052 | resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff; 1053 | rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0; 1054 | 1055 | // flush data segments 1056 | for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { 1057 | IKCPSEG *segment = iqueue_entry(p, IKCPSEG, node); 1058 | int needsend = 0; 1059 | if (segment->xmit == 0) { 1060 | needsend = 1; 1061 | segment->xmit++; 1062 | segment->rto = kcp->rx_rto; 1063 | segment->resendts = current + segment->rto + rtomin; 1064 | } 1065 | else if (_itimediff(current, segment->resendts) >= 0) { 1066 | needsend = 1; 1067 | segment->xmit++; 1068 | kcp->xmit++; 1069 | if (kcp->nodelay == 0) { 1070 | segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto); 1071 | } else { 1072 | IINT32 step = (kcp->nodelay < 2)? 1073 | ((IINT32)(segment->rto)) : kcp->rx_rto; 1074 | segment->rto += step / 2; 1075 | } 1076 | segment->resendts = current + segment->rto; 1077 | lost = 1; 1078 | } 1079 | else if (segment->fastack >= resent) { 1080 | if ((int)segment->xmit <= kcp->fastlimit || 1081 | kcp->fastlimit <= 0) { 1082 | needsend = 1; 1083 | segment->xmit++; 1084 | segment->fastack = 0; 1085 | segment->resendts = current + segment->rto; 1086 | change++; 1087 | } 1088 | } 1089 | 1090 | if (needsend) { 1091 | int need; 1092 | segment->ts = current; 1093 | segment->wnd = seg.wnd; 1094 | segment->una = kcp->rcv_nxt; 1095 | 1096 | size = (int)(ptr - buffer); 1097 | need = IKCP_OVERHEAD + segment->len; 1098 | 1099 | if (size + need > (int)kcp->mtu) { 1100 | ikcp_output(kcp, buffer, size); 1101 | ptr = buffer; 1102 | } 1103 | 1104 | ptr = ikcp_encode_seg(ptr, segment); 1105 | 1106 | if (segment->len > 0) { 1107 | memcpy(ptr, segment->data, segment->len); 1108 | ptr += segment->len; 1109 | } 1110 | 1111 | if (segment->xmit >= kcp->dead_link) { 1112 | kcp->state = (IUINT32)-1; 1113 | } 1114 | } 1115 | } 1116 | 1117 | // flash remain segments 1118 | size = (int)(ptr - buffer); 1119 | if (size > 0) { 1120 | ikcp_output(kcp, buffer, size); 1121 | } 1122 | 1123 | // update ssthresh 1124 | if (change) { 1125 | IUINT32 inflight = kcp->snd_nxt - kcp->snd_una; 1126 | kcp->ssthresh = inflight / 2; 1127 | if (kcp->ssthresh < IKCP_THRESH_MIN) 1128 | kcp->ssthresh = IKCP_THRESH_MIN; 1129 | kcp->cwnd = kcp->ssthresh + resent; 1130 | kcp->incr = kcp->cwnd * kcp->mss; 1131 | } 1132 | 1133 | if (lost) { 1134 | kcp->ssthresh = cwnd / 2; 1135 | if (kcp->ssthresh < IKCP_THRESH_MIN) 1136 | kcp->ssthresh = IKCP_THRESH_MIN; 1137 | kcp->cwnd = 1; 1138 | kcp->incr = kcp->mss; 1139 | } 1140 | 1141 | if (kcp->cwnd < 1) { 1142 | kcp->cwnd = 1; 1143 | kcp->incr = kcp->mss; 1144 | } 1145 | } 1146 | 1147 | 1148 | //--------------------------------------------------------------------- 1149 | // update state (call it repeatedly, every 10ms-100ms), or you can ask 1150 | // ikcp_check when to call it again (without ikcp_input/_send calling). 1151 | // 'current' - current timestamp in millisec. 1152 | //--------------------------------------------------------------------- 1153 | void ikcp_update(ikcpcb *kcp, IUINT32 current) 1154 | { 1155 | IINT32 slap; 1156 | 1157 | kcp->current = current; 1158 | 1159 | if (kcp->updated == 0) { 1160 | kcp->updated = 1; 1161 | kcp->ts_flush = kcp->current; 1162 | } 1163 | 1164 | slap = _itimediff(kcp->current, kcp->ts_flush); 1165 | 1166 | if (slap >= 10000 || slap < -10000) { 1167 | kcp->ts_flush = kcp->current; 1168 | slap = 0; 1169 | } 1170 | 1171 | if (slap >= 0) { 1172 | kcp->ts_flush += kcp->interval; 1173 | if (_itimediff(kcp->current, kcp->ts_flush) >= 0) { 1174 | kcp->ts_flush = kcp->current + kcp->interval; 1175 | } 1176 | ikcp_flush(kcp); 1177 | } 1178 | } 1179 | 1180 | 1181 | //--------------------------------------------------------------------- 1182 | // Determine when should you invoke ikcp_update: 1183 | // returns when you should invoke ikcp_update in millisec, if there 1184 | // is no ikcp_input/_send calling. you can call ikcp_update in that 1185 | // time, instead of call update repeatly. 1186 | // Important to reduce unnacessary ikcp_update invoking. use it to 1187 | // schedule ikcp_update (eg. implementing an epoll-like mechanism, 1188 | // or optimize ikcp_update when handling massive kcp connections) 1189 | //--------------------------------------------------------------------- 1190 | IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current) 1191 | { 1192 | IUINT32 ts_flush = kcp->ts_flush; 1193 | IINT32 tm_flush = 0x7fffffff; 1194 | IINT32 tm_packet = 0x7fffffff; 1195 | IUINT32 minimal = 0; 1196 | struct IQUEUEHEAD *p; 1197 | 1198 | if (kcp->updated == 0) { 1199 | return current; 1200 | } 1201 | 1202 | if (_itimediff(current, ts_flush) >= 10000 || 1203 | _itimediff(current, ts_flush) < -10000) { 1204 | ts_flush = current; 1205 | } 1206 | 1207 | if (_itimediff(current, ts_flush) >= 0) { 1208 | return current; 1209 | } 1210 | 1211 | tm_flush = _itimediff(ts_flush, current); 1212 | 1213 | for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { 1214 | const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); 1215 | IINT32 diff = _itimediff(seg->resendts, current); 1216 | if (diff <= 0) { 1217 | return current; 1218 | } 1219 | if (diff < tm_packet) tm_packet = diff; 1220 | } 1221 | 1222 | minimal = (IUINT32)(tm_packet < tm_flush ? tm_packet : tm_flush); 1223 | if (minimal >= kcp->interval) minimal = kcp->interval; 1224 | 1225 | return current + minimal; 1226 | } 1227 | 1228 | 1229 | 1230 | int ikcp_setmtu(ikcpcb *kcp, int mtu) 1231 | { 1232 | char *buffer; 1233 | if (mtu < 50 || mtu < (int)IKCP_OVERHEAD) 1234 | return -1; 1235 | buffer = (char*)ikcp_malloc((mtu + IKCP_OVERHEAD) * 3); 1236 | if (buffer == NULL) 1237 | return -2; 1238 | kcp->mtu = mtu; 1239 | kcp->mss = kcp->mtu - IKCP_OVERHEAD; 1240 | ikcp_free(kcp->buffer); 1241 | kcp->buffer = buffer; 1242 | return 0; 1243 | } 1244 | 1245 | int ikcp_interval(ikcpcb *kcp, int interval) 1246 | { 1247 | if (interval > 5000) interval = 5000; 1248 | else if (interval < 10) interval = 10; 1249 | kcp->interval = interval; 1250 | return 0; 1251 | } 1252 | 1253 | int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc) 1254 | { 1255 | if (nodelay >= 0) { 1256 | kcp->nodelay = nodelay; 1257 | if (nodelay) { 1258 | kcp->rx_minrto = IKCP_RTO_NDL; 1259 | } 1260 | else { 1261 | kcp->rx_minrto = IKCP_RTO_MIN; 1262 | } 1263 | } 1264 | if (interval >= 0) { 1265 | if (interval > 5000) interval = 5000; 1266 | else if (interval < 10) interval = 10; 1267 | kcp->interval = interval; 1268 | } 1269 | if (resend >= 0) { 1270 | kcp->fastresend = resend; 1271 | } 1272 | if (nc >= 0) { 1273 | kcp->nocwnd = nc; 1274 | } 1275 | return 0; 1276 | } 1277 | 1278 | 1279 | int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd) 1280 | { 1281 | if (kcp) { 1282 | if (sndwnd > 0) { 1283 | kcp->snd_wnd = sndwnd; 1284 | } 1285 | if (rcvwnd > 0) { // must >= max fragment size 1286 | kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV); 1287 | } 1288 | } 1289 | return 0; 1290 | } 1291 | 1292 | int ikcp_waitsnd(const ikcpcb *kcp) 1293 | { 1294 | return kcp->nsnd_buf + kcp->nsnd_que; 1295 | } 1296 | 1297 | 1298 | // read conv 1299 | IUINT32 ikcp_getconv(const void *ptr) 1300 | { 1301 | IUINT32 conv; 1302 | ikcp_decode32u((const char*)ptr, &conv); 1303 | return conv; 1304 | } 1305 | 1306 | 1307 | -------------------------------------------------------------------------------- /ikcp.h: -------------------------------------------------------------------------------- 1 | //===================================================================== 2 | // 3 | // KCP - A Better ARQ Protocol Implementation 4 | // skywind3000 (at) gmail.com, 2010-2011 5 | // 6 | // Features: 7 | // + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. 8 | // + Maximum RTT reduce three times vs tcp. 9 | // + Lightweight, distributed as a single source file. 10 | // 11 | //===================================================================== 12 | #ifndef __IKCP_H__ 13 | #define __IKCP_H__ 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | 20 | //===================================================================== 21 | // 32BIT INTEGER DEFINITION 22 | //===================================================================== 23 | #ifndef __INTEGER_32_BITS__ 24 | #define __INTEGER_32_BITS__ 25 | #if defined(_WIN64) || defined(WIN64) || defined(__amd64__) || \ 26 | defined(__x86_64) || defined(__x86_64__) || defined(_M_IA64) || \ 27 | defined(_M_AMD64) 28 | typedef unsigned int ISTDUINT32; 29 | typedef int ISTDINT32; 30 | #elif defined(_WIN32) || defined(WIN32) || defined(__i386__) || \ 31 | defined(__i386) || defined(_M_X86) 32 | typedef unsigned long ISTDUINT32; 33 | typedef long ISTDINT32; 34 | #elif defined(__MACOS__) 35 | typedef UInt32 ISTDUINT32; 36 | typedef SInt32 ISTDINT32; 37 | #elif defined(__APPLE__) && defined(__MACH__) 38 | #include 39 | typedef u_int32_t ISTDUINT32; 40 | typedef int32_t ISTDINT32; 41 | #elif defined(__BEOS__) 42 | #include 43 | typedef u_int32_t ISTDUINT32; 44 | typedef int32_t ISTDINT32; 45 | #elif (defined(_MSC_VER) || defined(__BORLANDC__)) && (!defined(__MSDOS__)) 46 | typedef unsigned __int32 ISTDUINT32; 47 | typedef __int32 ISTDINT32; 48 | #elif defined(__GNUC__) 49 | #include 50 | typedef uint32_t ISTDUINT32; 51 | typedef int32_t ISTDINT32; 52 | #else 53 | typedef unsigned long ISTDUINT32; 54 | typedef long ISTDINT32; 55 | #endif 56 | #endif 57 | 58 | 59 | //===================================================================== 60 | // Integer Definition 61 | //===================================================================== 62 | #ifndef __IINT8_DEFINED 63 | #define __IINT8_DEFINED 64 | typedef char IINT8; 65 | #endif 66 | 67 | #ifndef __IUINT8_DEFINED 68 | #define __IUINT8_DEFINED 69 | typedef unsigned char IUINT8; 70 | #endif 71 | 72 | #ifndef __IUINT16_DEFINED 73 | #define __IUINT16_DEFINED 74 | typedef unsigned short IUINT16; 75 | #endif 76 | 77 | #ifndef __IINT16_DEFINED 78 | #define __IINT16_DEFINED 79 | typedef short IINT16; 80 | #endif 81 | 82 | #ifndef __IINT32_DEFINED 83 | #define __IINT32_DEFINED 84 | typedef ISTDINT32 IINT32; 85 | #endif 86 | 87 | #ifndef __IUINT32_DEFINED 88 | #define __IUINT32_DEFINED 89 | typedef ISTDUINT32 IUINT32; 90 | #endif 91 | 92 | #ifndef __IINT64_DEFINED 93 | #define __IINT64_DEFINED 94 | #if defined(_MSC_VER) || defined(__BORLANDC__) 95 | typedef __int64 IINT64; 96 | #else 97 | typedef long long IINT64; 98 | #endif 99 | #endif 100 | 101 | #ifndef __IUINT64_DEFINED 102 | #define __IUINT64_DEFINED 103 | #if defined(_MSC_VER) || defined(__BORLANDC__) 104 | typedef unsigned __int64 IUINT64; 105 | #else 106 | typedef unsigned long long IUINT64; 107 | #endif 108 | #endif 109 | 110 | #ifndef INLINE 111 | #if defined(__GNUC__) 112 | 113 | #if (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) 114 | #define INLINE __inline__ __attribute__((always_inline)) 115 | #else 116 | #define INLINE __inline__ 117 | #endif 118 | 119 | #elif (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__)) 120 | #define INLINE __inline 121 | #else 122 | #define INLINE 123 | #endif 124 | #endif 125 | 126 | #if (!defined(__cplusplus)) && (!defined(inline)) 127 | #define inline INLINE 128 | #endif 129 | 130 | 131 | //===================================================================== 132 | // QUEUE DEFINITION 133 | //===================================================================== 134 | #ifndef __IQUEUE_DEF__ 135 | #define __IQUEUE_DEF__ 136 | 137 | struct IQUEUEHEAD { 138 | struct IQUEUEHEAD *next, *prev; 139 | }; 140 | 141 | typedef struct IQUEUEHEAD iqueue_head; 142 | 143 | 144 | //--------------------------------------------------------------------- 145 | // queue init 146 | //--------------------------------------------------------------------- 147 | #define IQUEUE_HEAD_INIT(name) { &(name), &(name) } 148 | #define IQUEUE_HEAD(name) \ 149 | struct IQUEUEHEAD name = IQUEUE_HEAD_INIT(name) 150 | 151 | #define IQUEUE_INIT(ptr) ( \ 152 | (ptr)->next = (ptr), (ptr)->prev = (ptr)) 153 | 154 | #define IOFFSETOF(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 155 | 156 | #define ICONTAINEROF(ptr, type, member) ( \ 157 | (type*)( ((char*)((type*)ptr)) - IOFFSETOF(type, member)) ) 158 | 159 | #define IQUEUE_ENTRY(ptr, type, member) ICONTAINEROF(ptr, type, member) 160 | 161 | 162 | //--------------------------------------------------------------------- 163 | // queue operation 164 | //--------------------------------------------------------------------- 165 | #define IQUEUE_ADD(node, head) ( \ 166 | (node)->prev = (head), (node)->next = (head)->next, \ 167 | (head)->next->prev = (node), (head)->next = (node)) 168 | 169 | #define IQUEUE_ADD_TAIL(node, head) ( \ 170 | (node)->prev = (head)->prev, (node)->next = (head), \ 171 | (head)->prev->next = (node), (head)->prev = (node)) 172 | 173 | #define IQUEUE_DEL_BETWEEN(p, n) ((n)->prev = (p), (p)->next = (n)) 174 | 175 | #define IQUEUE_DEL(entry) (\ 176 | (entry)->next->prev = (entry)->prev, \ 177 | (entry)->prev->next = (entry)->next, \ 178 | (entry)->next = 0, (entry)->prev = 0) 179 | 180 | #define IQUEUE_DEL_INIT(entry) do { \ 181 | IQUEUE_DEL(entry); IQUEUE_INIT(entry); } while (0) 182 | 183 | #define IQUEUE_IS_EMPTY(entry) ((entry) == (entry)->next) 184 | 185 | #define iqueue_init IQUEUE_INIT 186 | #define iqueue_entry IQUEUE_ENTRY 187 | #define iqueue_add IQUEUE_ADD 188 | #define iqueue_add_tail IQUEUE_ADD_TAIL 189 | #define iqueue_del IQUEUE_DEL 190 | #define iqueue_del_init IQUEUE_DEL_INIT 191 | #define iqueue_is_empty IQUEUE_IS_EMPTY 192 | 193 | #define IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) \ 194 | for ((iterator) = iqueue_entry((head)->next, TYPE, MEMBER); \ 195 | &((iterator)->MEMBER) != (head); \ 196 | (iterator) = iqueue_entry((iterator)->MEMBER.next, TYPE, MEMBER)) 197 | 198 | #define iqueue_foreach(iterator, head, TYPE, MEMBER) \ 199 | IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) 200 | 201 | #define iqueue_foreach_entry(pos, head) \ 202 | for( (pos) = (head)->next; (pos) != (head) ; (pos) = (pos)->next ) 203 | 204 | 205 | #define __iqueue_splice(list, head) do { \ 206 | iqueue_head *first = (list)->next, *last = (list)->prev; \ 207 | iqueue_head *at = (head)->next; \ 208 | (first)->prev = (head), (head)->next = (first); \ 209 | (last)->next = (at), (at)->prev = (last); } while (0) 210 | 211 | #define iqueue_splice(list, head) do { \ 212 | if (!iqueue_is_empty(list)) __iqueue_splice(list, head); } while (0) 213 | 214 | #define iqueue_splice_init(list, head) do { \ 215 | iqueue_splice(list, head); iqueue_init(list); } while (0) 216 | 217 | 218 | #ifdef _MSC_VER 219 | #pragma warning(disable:4311) 220 | #pragma warning(disable:4312) 221 | #pragma warning(disable:4996) 222 | #endif 223 | 224 | #endif 225 | 226 | 227 | //--------------------------------------------------------------------- 228 | // BYTE ORDER & ALIGNMENT 229 | //--------------------------------------------------------------------- 230 | #ifndef IWORDS_BIG_ENDIAN 231 | #ifdef _BIG_ENDIAN_ 232 | #if _BIG_ENDIAN_ 233 | #define IWORDS_BIG_ENDIAN 1 234 | #endif 235 | #endif 236 | #ifndef IWORDS_BIG_ENDIAN 237 | #if defined(__hppa__) || \ 238 | defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ 239 | (defined(__MIPS__) && defined(__MIPSEB__)) || \ 240 | defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ 241 | defined(__sparc__) || defined(__powerpc__) || \ 242 | defined(__mc68000__) || defined(__s390x__) || defined(__s390__) 243 | #define IWORDS_BIG_ENDIAN 1 244 | #endif 245 | #endif 246 | #ifndef IWORDS_BIG_ENDIAN 247 | #define IWORDS_BIG_ENDIAN 0 248 | #endif 249 | #endif 250 | 251 | #ifndef IWORDS_MUST_ALIGN 252 | #if defined(__i386__) || defined(__i386) || defined(_i386_) 253 | #define IWORDS_MUST_ALIGN 0 254 | #elif defined(_M_IX86) || defined(_X86_) || defined(__x86_64__) 255 | #define IWORDS_MUST_ALIGN 0 256 | #elif defined(__amd64) || defined(__amd64__) 257 | #define IWORDS_MUST_ALIGN 0 258 | #else 259 | #define IWORDS_MUST_ALIGN 1 260 | #endif 261 | #endif 262 | 263 | 264 | //===================================================================== 265 | // SEGMENT 266 | //===================================================================== 267 | struct IKCPSEG 268 | { 269 | struct IQUEUEHEAD node; 270 | IUINT32 conv; 271 | IUINT32 cmd; 272 | IUINT32 frg; 273 | IUINT32 wnd; 274 | IUINT32 ts; 275 | IUINT32 sn; 276 | IUINT32 una; 277 | IUINT32 len; 278 | IUINT32 resendts; 279 | IUINT32 rto; 280 | IUINT32 fastack; 281 | IUINT32 xmit; 282 | char data[1]; 283 | }; 284 | 285 | 286 | //--------------------------------------------------------------------- 287 | // IKCPCB 288 | //--------------------------------------------------------------------- 289 | struct IKCPCB 290 | { 291 | IUINT32 conv, mtu, mss, state; 292 | IUINT32 snd_una, snd_nxt, rcv_nxt; 293 | IUINT32 ts_recent, ts_lastack, ssthresh; 294 | IINT32 rx_rttval, rx_srtt, rx_rto, rx_minrto; 295 | IUINT32 snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe; 296 | IUINT32 current, interval, ts_flush, xmit; 297 | IUINT32 nrcv_buf, nsnd_buf; 298 | IUINT32 nrcv_que, nsnd_que; 299 | IUINT32 nodelay, updated; 300 | IUINT32 ts_probe, probe_wait; 301 | IUINT32 dead_link, incr; 302 | struct IQUEUEHEAD snd_queue; 303 | struct IQUEUEHEAD rcv_queue; 304 | struct IQUEUEHEAD snd_buf; 305 | struct IQUEUEHEAD rcv_buf; 306 | IUINT32 *acklist; 307 | IUINT32 ackcount; 308 | IUINT32 ackblock; 309 | void *user; 310 | char *buffer; 311 | int fastresend; 312 | int fastlimit; 313 | int nocwnd, stream; 314 | int logmask; 315 | int (*output)(const char *buf, int len, struct IKCPCB *kcp, void *user); 316 | void (*writelog)(const char *log, struct IKCPCB *kcp, void *user); 317 | }; 318 | 319 | 320 | typedef struct IKCPCB ikcpcb; 321 | 322 | #define IKCP_LOG_OUTPUT 1 323 | #define IKCP_LOG_INPUT 2 324 | #define IKCP_LOG_SEND 4 325 | #define IKCP_LOG_RECV 8 326 | #define IKCP_LOG_IN_DATA 16 327 | #define IKCP_LOG_IN_ACK 32 328 | #define IKCP_LOG_IN_PROBE 64 329 | #define IKCP_LOG_IN_WINS 128 330 | #define IKCP_LOG_OUT_DATA 256 331 | #define IKCP_LOG_OUT_ACK 512 332 | #define IKCP_LOG_OUT_PROBE 1024 333 | #define IKCP_LOG_OUT_WINS 2048 334 | 335 | #ifdef __cplusplus 336 | extern "C" { 337 | #endif 338 | 339 | //--------------------------------------------------------------------- 340 | // interface 341 | //--------------------------------------------------------------------- 342 | 343 | // create a new kcp control object, 'conv' must equal in two endpoint 344 | // from the same connection. 'user' will be passed to the output callback 345 | // output callback can be setup like this: 'kcp->output = my_udp_output' 346 | ikcpcb* ikcp_create(IUINT32 conv, void *user); 347 | 348 | // release kcp control object 349 | void ikcp_release(ikcpcb *kcp); 350 | 351 | // set output callback, which will be invoked by kcp 352 | void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, 353 | ikcpcb *kcp, void *user)); 354 | 355 | // user/upper level recv: returns size, returns below zero for EAGAIN 356 | int ikcp_recv(ikcpcb *kcp, char *buffer, int len); 357 | 358 | // user/upper level send, returns below zero for error 359 | int ikcp_send(ikcpcb *kcp, const char *buffer, int len); 360 | 361 | // update state (call it repeatedly, every 10ms-100ms), or you can ask 362 | // ikcp_check when to call it again (without ikcp_input/_send calling). 363 | // 'current' - current timestamp in millisec. 364 | void ikcp_update(ikcpcb *kcp, IUINT32 current); 365 | 366 | // Determine when should you invoke ikcp_update: 367 | // returns when you should invoke ikcp_update in millisec, if there 368 | // is no ikcp_input/_send calling. you can call ikcp_update in that 369 | // time, instead of call update repeatly. 370 | // Important to reduce unnacessary ikcp_update invoking. use it to 371 | // schedule ikcp_update (eg. implementing an epoll-like mechanism, 372 | // or optimize ikcp_update when handling massive kcp connections) 373 | IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current); 374 | 375 | // when you received a low level packet (eg. UDP packet), call it 376 | int ikcp_input(ikcpcb *kcp, const char *data, long size); 377 | 378 | // flush pending data 379 | void ikcp_flush(ikcpcb *kcp); 380 | 381 | // check the size of next message in the recv queue 382 | int ikcp_peeksize(const ikcpcb *kcp); 383 | 384 | // change MTU size, default is 1400 385 | int ikcp_setmtu(ikcpcb *kcp, int mtu); 386 | 387 | // set maximum window size: sndwnd=32, rcvwnd=32 by default 388 | int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd); 389 | 390 | // get how many packet is waiting to be sent 391 | int ikcp_waitsnd(const ikcpcb *kcp); 392 | 393 | // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) 394 | // nodelay: 0:disable(default), 1:enable 395 | // interval: internal update timer interval in millisec, default is 100ms 396 | // resend: 0:disable fast resend(default), 1:enable fast resend 397 | // nc: 0:normal congestion control(default), 1:disable congestion control 398 | int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc); 399 | 400 | 401 | void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...); 402 | 403 | // setup allocator 404 | void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)); 405 | 406 | // read conv 407 | IUINT32 ikcp_getconv(const void *ptr); 408 | 409 | 410 | #ifdef __cplusplus 411 | } 412 | #endif 413 | 414 | #endif 415 | 416 | 417 | -------------------------------------------------------------------------------- /images/donation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skywind3000/kcp/f4f3a89cc632647dabdcb146932d2afd5591e62e/images/donation.png -------------------------------------------------------------------------------- /images/spatialos-25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skywind3000/kcp/f4f3a89cc632647dabdcb146932d2afd5591e62e/images/spatialos-25.png -------------------------------------------------------------------------------- /images/spatialos-50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skywind3000/kcp/f4f3a89cc632647dabdcb146932d2afd5591e62e/images/spatialos-50.png -------------------------------------------------------------------------------- /kcp.svg: -------------------------------------------------------------------------------- 1 | KCPKCPPoweredPowered -------------------------------------------------------------------------------- /protocol.txt: -------------------------------------------------------------------------------- 1 | KCP PROTOCOL SPECIFICATION 2 | 3 | 4 | 1. Packet (aka. segment) Structure 5 | 6 | KCP has only one kind of segment: both the data and control messages are 7 | encoded into the same structure and share the same header. 8 | 9 | The KCP packet (aka. segment) structure is as following: 10 | 11 | 0 4 5 6 8 (BYTE) 12 | +---------------+---+---+-------+ 13 | | conv |cmd|frg| wnd | 14 | +---------------+---+---+-------+ 8 15 | | ts | sn | 16 | +---------------+---------------+ 16 17 | | una | len | 18 | +---------------+---------------+ 24 19 | | | 20 | | DATA (optional) | 21 | | | 22 | +-------------------------------+ 23 | 24 | 25 | - conv: conversation id (32 bits integer) 26 | 27 | The conversation id is used to identify each connection, which will not change 28 | during the connection life-time. 29 | 30 | It is represented by a 32 bits integer which is given at the moment the KCP 31 | control block (aka. struct ikcpcb, or kcp object) has been created. Each 32 | packet sent out will carry the conversation id in the first 4 bytes and a 33 | packet from remote endpoint will not be accepted if it has a different 34 | conversation id. 35 | 36 | The value can be any random number, but in practice, both side between a 37 | connection will have many KCP objects (or control block) storing in the 38 | containers like a map or an array. A index is used as the key to look up one 39 | KCP object from the container. 40 | 41 | So, the higher 16 bits of conversation id can be used as caller's index while 42 | the lower 16 bits can be used as callee's index. KCP will not handle 43 | handshake, and the index in both side can be decided and exchanged after 44 | connection establish. 45 | 46 | When you receive and accept a remote packet, the local index can be extracted 47 | from the conversation id and the kcp object which is in charge of this 48 | connection can be find out from your map or array. 49 | 50 | 51 | - cmd: command 52 | 53 | - frg: fragment count 54 | 55 | - wnd: window size 56 | 57 | - ts: timestamp 58 | 59 | - sn: serial number 60 | 61 | - una: un-acknowledged serial number 62 | 63 | 64 | # vim: set ts=4 sw=4 tw=0 noet cc=78 wrap textwidth=78 : 65 | 66 | -------------------------------------------------------------------------------- /test.cpp: -------------------------------------------------------------------------------- 1 | //===================================================================== 2 | // 3 | // test.cpp - kcp 测试用例 4 | // 5 | // 说明: 6 | // gcc test.cpp -o test -lstdc++ 7 | // 8 | //===================================================================== 9 | 10 | #include 11 | #include 12 | 13 | #include "test.h" 14 | #include "ikcp.c" 15 | 16 | 17 | // 模拟网络 18 | LatencySimulator *vnet; 19 | 20 | // 模拟网络:模拟发送一个 udp包 21 | int udp_output(const char *buf, int len, ikcpcb *kcp, void *user) 22 | { 23 | union { int id; void *ptr; } parameter; 24 | parameter.ptr = user; 25 | vnet->send(parameter.id, buf, len); 26 | return 0; 27 | } 28 | 29 | // 测试用例 30 | void test(int mode) 31 | { 32 | // 创建模拟网络:丢包率10%,Rtt 60ms~125ms 33 | vnet = new LatencySimulator(10, 60, 125); 34 | 35 | // 创建两个端点的 kcp对象,第一个参数 conv是会话编号,同一个会话需要相同 36 | // 最后一个是 user参数,用来传递标识 37 | ikcpcb *kcp1 = ikcp_create(0x11223344, (void*)0); 38 | ikcpcb *kcp2 = ikcp_create(0x11223344, (void*)1); 39 | 40 | // 设置kcp的下层输出,这里为 udp_output,模拟udp网络输出函数 41 | kcp1->output = udp_output; 42 | kcp2->output = udp_output; 43 | 44 | IUINT32 current = iclock(); 45 | IUINT32 slap = current + 20; 46 | IUINT32 index = 0; 47 | IUINT32 next = 0; 48 | IINT64 sumrtt = 0; 49 | int count = 0; 50 | int maxrtt = 0; 51 | 52 | // 配置窗口大小:平均延迟200ms,每20ms发送一个包, 53 | // 而考虑到丢包重发,设置最大收发窗口为128 54 | ikcp_wndsize(kcp1, 128, 128); 55 | ikcp_wndsize(kcp2, 128, 128); 56 | 57 | // 判断测试用例的模式 58 | if (mode == 0) { 59 | // 默认模式 60 | ikcp_nodelay(kcp1, 0, 10, 0, 0); 61 | ikcp_nodelay(kcp2, 0, 10, 0, 0); 62 | } 63 | else if (mode == 1) { 64 | // 普通模式,关闭流控等 65 | ikcp_nodelay(kcp1, 0, 10, 0, 1); 66 | ikcp_nodelay(kcp2, 0, 10, 0, 1); 67 | } else { 68 | // 启动快速模式 69 | // 第二个参数 nodelay-启用以后若干常规加速将启动 70 | // 第三个参数 interval为内部处理时钟,默认设置为 10ms 71 | // 第四个参数 resend为快速重传指标,设置为2 72 | // 第五个参数 为是否禁用常规流控,这里禁止 73 | ikcp_nodelay(kcp1, 2, 10, 2, 1); 74 | ikcp_nodelay(kcp2, 2, 10, 2, 1); 75 | kcp1->rx_minrto = 10; 76 | kcp1->fastresend = 1; 77 | } 78 | 79 | 80 | char buffer[2000]; 81 | int hr; 82 | 83 | IUINT32 ts1 = iclock(); 84 | 85 | while (1) { 86 | isleep(1); 87 | current = iclock(); 88 | ikcp_update(kcp1, iclock()); 89 | ikcp_update(kcp2, iclock()); 90 | 91 | // 每隔 20ms,kcp1发送数据 92 | for (; current >= slap; slap += 20) { 93 | ((IUINT32*)buffer)[0] = index++; 94 | ((IUINT32*)buffer)[1] = current; 95 | 96 | // 发送上层协议包 97 | ikcp_send(kcp1, buffer, 8); 98 | } 99 | 100 | // 处理虚拟网络:检测是否有udp包从p1->p2 101 | while (1) { 102 | hr = vnet->recv(1, buffer, 2000); 103 | if (hr < 0) break; 104 | // 如果 p2收到udp,则作为下层协议输入到kcp2 105 | ikcp_input(kcp2, buffer, hr); 106 | } 107 | 108 | // 处理虚拟网络:检测是否有udp包从p2->p1 109 | while (1) { 110 | hr = vnet->recv(0, buffer, 2000); 111 | if (hr < 0) break; 112 | // 如果 p1收到udp,则作为下层协议输入到kcp1 113 | ikcp_input(kcp1, buffer, hr); 114 | } 115 | 116 | // kcp2接收到任何包都返回回去 117 | while (1) { 118 | hr = ikcp_recv(kcp2, buffer, 10); 119 | // 没有收到包就退出 120 | if (hr < 0) break; 121 | // 如果收到包就回射 122 | ikcp_send(kcp2, buffer, hr); 123 | } 124 | 125 | // kcp1收到kcp2的回射数据 126 | while (1) { 127 | hr = ikcp_recv(kcp1, buffer, 10); 128 | // 没有收到包就退出 129 | if (hr < 0) break; 130 | IUINT32 sn = *(IUINT32*)(buffer + 0); 131 | IUINT32 ts = *(IUINT32*)(buffer + 4); 132 | IUINT32 rtt = current - ts; 133 | 134 | if (sn != next) { 135 | // 如果收到的包不连续 136 | printf("ERROR sn %d<->%d\n", (int)count, (int)next); 137 | return; 138 | } 139 | 140 | next++; 141 | sumrtt += rtt; 142 | count++; 143 | if (rtt > (IUINT32)maxrtt) maxrtt = rtt; 144 | 145 | printf("[RECV] mode=%d sn=%d rtt=%d\n", mode, (int)sn, (int)rtt); 146 | } 147 | if (next > 1000) break; 148 | } 149 | 150 | ts1 = iclock() - ts1; 151 | 152 | ikcp_release(kcp1); 153 | ikcp_release(kcp2); 154 | 155 | const char *names[3] = { "default", "normal", "fast" }; 156 | printf("%s mode result (%dms):\n", names[mode], (int)ts1); 157 | printf("avgrtt=%d maxrtt=%d tx=%d\n", (int)(sumrtt / count), (int)maxrtt, (int)vnet->tx1); 158 | printf("press enter to next ...\n"); 159 | char ch; scanf("%c", &ch); 160 | } 161 | 162 | int main() 163 | { 164 | test(0); // 默认模式,类似 TCP:正常模式,无快速重传,常规流控 165 | test(1); // 普通模式,关闭流控等 166 | test(2); // 快速模式,所有开关都打开,且关闭流控 167 | return 0; 168 | } 169 | 170 | /* 171 | default mode result (20917ms): 172 | avgrtt=740 maxrtt=1507 173 | 174 | normal mode result (20131ms): 175 | avgrtt=156 maxrtt=571 176 | 177 | fast mode result (20207ms): 178 | avgrtt=138 maxrtt=392 179 | */ 180 | 181 | 182 | -------------------------------------------------------------------------------- /test.h: -------------------------------------------------------------------------------- 1 | #ifndef __TEST_H__ 2 | #define __TEST_H__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "ikcp.h" 11 | 12 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 13 | #include 14 | #elif !defined(__unix) 15 | #define __unix 16 | #endif 17 | 18 | #ifdef __unix 19 | #include 20 | #include 21 | #include 22 | #include 23 | #endif 24 | 25 | /* get system time */ 26 | static inline void itimeofday(long *sec, long *usec) 27 | { 28 | #if defined(__unix) 29 | struct timeval time; 30 | gettimeofday(&time, NULL); 31 | if (sec) *sec = time.tv_sec; 32 | if (usec) *usec = time.tv_usec; 33 | #else 34 | static long mode = 0, addsec = 0; 35 | BOOL retval; 36 | static IINT64 freq = 1; 37 | IINT64 qpc; 38 | if (mode == 0) { 39 | retval = QueryPerformanceFrequency((LARGE_INTEGER*)&freq); 40 | freq = (freq == 0)? 1 : freq; 41 | retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); 42 | addsec = (long)time(NULL); 43 | addsec = addsec - (long)((qpc / freq) & 0x7fffffff); 44 | mode = 1; 45 | } 46 | retval = QueryPerformanceCounter((LARGE_INTEGER*)&qpc); 47 | retval = retval * 2; 48 | if (sec) *sec = (long)(qpc / freq) + addsec; 49 | if (usec) *usec = (long)((qpc % freq) * 1000000 / freq); 50 | #endif 51 | } 52 | 53 | /* get clock in millisecond 64 */ 54 | static inline IINT64 iclock64(void) 55 | { 56 | long s, u; 57 | IINT64 value; 58 | itimeofday(&s, &u); 59 | value = ((IINT64)s) * 1000 + (u / 1000); 60 | return value; 61 | } 62 | 63 | static inline IUINT32 iclock() 64 | { 65 | return (IUINT32)(iclock64() & 0xfffffffful); 66 | } 67 | 68 | /* sleep in millisecond */ 69 | static inline void isleep(unsigned long millisecond) 70 | { 71 | #ifdef __unix /* usleep( time * 1000 ); */ 72 | struct timespec ts; 73 | ts.tv_sec = (time_t)(millisecond / 1000); 74 | ts.tv_nsec = (long)((millisecond % 1000) * 1000000); 75 | /*nanosleep(&ts, NULL);*/ 76 | usleep((millisecond << 10) - (millisecond << 4) - (millisecond << 3)); 77 | #elif defined(_WIN32) 78 | Sleep(millisecond); 79 | #endif 80 | } 81 | 82 | #ifdef __cplusplus 83 | #include 84 | #include 85 | 86 | // 带延迟的数据包 87 | class DelayPacket 88 | { 89 | public: 90 | virtual ~DelayPacket() { 91 | if (_ptr) delete[] _ptr; 92 | _ptr = NULL; 93 | } 94 | 95 | DelayPacket(int size, const void *src = NULL) { 96 | _ptr = new unsigned char[size]; 97 | _size = size; 98 | if (src) { 99 | memcpy(_ptr, src, size); 100 | } 101 | } 102 | 103 | unsigned char* ptr() { return _ptr; } 104 | const unsigned char* ptr() const { return _ptr; } 105 | 106 | int size() const { return _size; } 107 | IUINT32 ts() const { return _ts; } 108 | void setts(IUINT32 ts) { _ts = ts; } 109 | 110 | protected: 111 | unsigned char *_ptr; 112 | int _size; 113 | IUINT32 _ts; 114 | }; 115 | 116 | // 均匀分布的随机数 117 | class Random 118 | { 119 | public: 120 | Random(int size) { 121 | this->size = 0; 122 | seeds.resize(size); 123 | } 124 | 125 | int random() { 126 | int x, i; 127 | if (seeds.size() == 0) return 0; 128 | if (size == 0) { 129 | for (i = 0; i < (int)seeds.size(); i++) { 130 | seeds[i] = i; 131 | } 132 | size = (int)seeds.size(); 133 | } 134 | i = rand() % size; 135 | x = seeds[i]; 136 | seeds[i] = seeds[--size]; 137 | return x; 138 | } 139 | 140 | protected: 141 | int size; 142 | std::vector seeds; 143 | }; 144 | 145 | // 网络延迟模拟器 146 | class LatencySimulator 147 | { 148 | public: 149 | 150 | virtual ~LatencySimulator() { 151 | clear(); 152 | } 153 | 154 | // lostrate: 往返一周丢包率的百分比,默认 10% 155 | // rttmin:rtt最小值,默认 60 156 | // rttmax:rtt最大值,默认 125 157 | LatencySimulator(int lostrate = 10, int rttmin = 60, int rttmax = 125, int nmax = 1000): 158 | r12(100), r21(100) { 159 | current = iclock(); 160 | this->lostrate = lostrate / 2; // 上面数据是往返丢包率,单程除以2 161 | this->rttmin = rttmin / 2; 162 | this->rttmax = rttmax / 2; 163 | this->nmax = nmax; 164 | tx1 = tx2 = 0; 165 | } 166 | 167 | // 清除数据 168 | void clear() { 169 | DelayTunnel::iterator it; 170 | for (it = p12.begin(); it != p12.end(); it++) { 171 | delete *it; 172 | } 173 | for (it = p21.begin(); it != p21.end(); it++) { 174 | delete *it; 175 | } 176 | p12.clear(); 177 | p21.clear(); 178 | } 179 | 180 | // 发送数据 181 | // peer - 端点0/1,从0发送,从1接收;从1发送从0接收 182 | void send(int peer, const void *data, int size) { 183 | if (peer == 0) { 184 | tx1++; 185 | if (r12.random() < lostrate) return; 186 | if ((int)p12.size() >= nmax) return; 187 | } else { 188 | tx2++; 189 | if (r21.random() < lostrate) return; 190 | if ((int)p21.size() >= nmax) return; 191 | } 192 | DelayPacket *pkt = new DelayPacket(size, data); 193 | current = iclock(); 194 | IUINT32 delay = rttmin; 195 | if (rttmax > rttmin) delay += rand() % (rttmax - rttmin); 196 | pkt->setts(current + delay); 197 | if (peer == 0) { 198 | p12.push_back(pkt); 199 | } else { 200 | p21.push_back(pkt); 201 | } 202 | } 203 | 204 | // 接收数据 205 | int recv(int peer, void *data, int maxsize) { 206 | DelayTunnel::iterator it; 207 | if (peer == 0) { 208 | it = p21.begin(); 209 | if (p21.size() == 0) return -1; 210 | } else { 211 | it = p12.begin(); 212 | if (p12.size() == 0) return -1; 213 | } 214 | DelayPacket *pkt = *it; 215 | current = iclock(); 216 | if (current < pkt->ts()) return -2; 217 | if (maxsize < pkt->size()) return -3; 218 | if (peer == 0) { 219 | p21.erase(it); 220 | } else { 221 | p12.erase(it); 222 | } 223 | maxsize = pkt->size(); 224 | memcpy(data, pkt->ptr(), maxsize); 225 | delete pkt; 226 | return maxsize; 227 | } 228 | 229 | public: 230 | int tx1; 231 | int tx2; 232 | 233 | protected: 234 | IUINT32 current; 235 | int lostrate; 236 | int rttmin; 237 | int rttmax; 238 | int nmax; 239 | typedef std::list DelayTunnel; 240 | DelayTunnel p12; 241 | DelayTunnel p21; 242 | Random r12; 243 | Random r21; 244 | }; 245 | 246 | #endif 247 | 248 | #endif 249 | 250 | 251 | --------------------------------------------------------------------------------