256 Commits
1.2 ... master

Author SHA1 Message Date
Linwei
b1a7a2101d Merge pull request #460 from jokelbaf/master
Add kcp.kt to the list of related applications in README
2026-06-23 14:21:10 +08:00
jokelbaf
f4694f598d Add kcp.kt to the list of related applications in README 2026-06-23 01:50:52 +03:00
Linwei
c102b9b7f5 Merge pull request #459 from lingxiaoyiyu-hub/fix/typo-in-readme
docs: fix typo in README.md
2026-06-20 11:38:47 +08:00
XIAOCheng
37c1c01da1 docs: fix typo in README.md
- 'writen' -> 'written'
2026-06-19 15:19:22 +08:00
Linwei
9aed788c9d Merge pull request #458 from new1271/master
Add KcpSharpN to README.md and README.en.md
2026-05-25 10:10:03 +08:00
Rice Tea
2e1bd4a2c1 Update the description for KcpSharpN 2026-05-24 17:57:19 +08:00
Rice Tea
1ca0b18a43 Added KcpSharpN to the README.en.md 2026-05-24 17:53:24 +08:00
Rice Tea
284a977276 Added KcpSharpN to the README.md 2026-05-24 17:46:07 +08:00
skywind3000
fbd716b257 Merge branch 'v2' 2026-05-16 01:52:21 +08:00
skywind3000
7346e366f1 simple pacing 2026-05-16 01:21:36 +08:00
skywind3000
31c2ae0529 Merge branch 'v2' 2026-05-16 00:20:17 +08:00
skywind3000
e8fc1fb840 add necessary information to the callbacks 2026-05-16 00:11:40 +08:00
skywind3000
46eed3ef30 Merge branch 'master' of https://github.com/skywind3000/kcp 2026-05-15 22:51:28 +08:00
skywind3000
19459fa64d kcp-2.0.0: a pluggable congestion control system that allows you to replace the built-in algorithm by installing callbacks without modifying KCP code. 2026-05-15 22:51:19 +08:00
skywind3000
b6953419c9 remove unnecessary xmit in the callback 2026-05-15 22:50:50 +08:00
skywind3000
fddd37687d Merge branch 'v2' 2026-05-15 21:40:51 +08:00
skywind3000
b3607a6d7d fix: on_pkt_sent lacks xmit information 2026-05-15 21:40:30 +08:00
skywind3000
8aded6f405 remove files 2026-05-15 17:04:51 +08:00
skywind3000
c2ffc0554f optimize cwnd calculation in the default congestion control 2026-05-15 17:02:03 +08:00
skywind3000
d29b83e72f update testing support files 2026-05-15 08:42:56 +08:00
skywind3000
32da082e52 kcp-2.0.0: a pluggable congestion control system that allows you to replace the built-in algorithm by installing callbacks without modifying KCP code. 2026-05-15 07:43:46 +08:00
skywind3000
63c8887987 remove test files 2026-05-15 07:36:16 +08:00
skywind3000
55ae1be446 add netsim.h and netstats.h 2026-05-14 15:49:10 +08:00
skywind3000
d13de3b19d congestion control: basically finish 2026-05-14 11:34:05 +08:00
skywind3000
8b32a64326 congestion control: stage 4 2026-05-14 11:01:20 +08:00
skywind3000
0d9515a42a congestion control: stage 3 2026-05-14 10:49:39 +08:00
skywind3000
b1af1c06f0 congestion control: stage 2 2026-05-14 10:39:48 +08:00
skywind3000
7f0fe725c3 congestion control: definitions 2026-05-14 10:00:27 +08:00
skywind3000
ed6e480b0e pluggable congestion control stage1 2026-05-14 09:55:55 +08:00
Linwei
8004f7eba5 Update CMakeLists.txt 2026-05-01 21:54:42 +08:00
Linwei
f4f3a89cc6 Merge pull request #444 from MouseBrilliant/patch-1
Update README.en.md
2025-04-22 15:37:00 +08:00
MouseBrilliant
db4526a01b Update README.en.md
I rewrote the document, preserving the original message. The initial document was difficult for native English speakers to read and comprehend. I have cleaned up some things to make it straightforward for readers with any level of English proficiency.
2025-04-22 01:13:59 -04:00
Linwei
ec72e34715 Merge pull request #443 from myd7349/update-cmake-version
fix configuration error with CMake 4.0
2025-04-09 14:32:26 +08:00
myd7349
fbf73d19a1 update cmake minimum version 2025-04-08 22:48:52 +08:00
Linwei
7f9805887b Merge pull request #435 from quqiOnfree/master
添加现代C++/Asio的KCP支持
2024-12-01 01:49:42 +08:00
Xuan Xiao
8f706ad697 Update README 2024-11-30 15:30:24 +00:00
Linwei
b4a0aba445 Merge pull request #434 from wpjscc-labs/master
php kcp 扩展
2024-11-23 17:30:32 +08:00
wpjscc
bfe542b9ec php kcp 扩展 2024-11-23 08:52:28 +08:00
skywind3000
ecafc2b299 update docs 2024-10-16 16:31:07 +08:00
skywind3000
fcd439304f update docs 2024-10-16 16:29:33 +08:00
skywind3000
bb9416a705 update docs 2024-10-16 16:27:39 +08:00
skywind3000
0d85027370 update docs 2024-10-16 16:26:45 +08:00
skywind3000
8e7f855a1f update doc 2024-10-16 16:25:11 +08:00
skywind3000
94385a10f8 update gitignore 2024-10-11 22:29:05 +08:00
Linwei
7440cdaeb7 Merge pull request #419 from Molth/master
add kcptransport to readme
2024-07-18 11:07:25 +08:00
Nevin
924a190ee0 add kcptransport to readme 2024-07-18 10:05:22 +08:00
Linwei
7a878bf358 Merge pull request #409 from Alan-yly/master
添加IKCP_FASTACK_CONSERVE宏  避免多次触发快重传
2024-04-09 15:37:10 +08:00
Alan-yly
49bea97d33 添加IKCP_FASTACK_CONSERVE宏 避免多次触发快重传 2024-04-09 14:01:35 +08:00
skywind3000
f2aa30ea21 ikcp_send 返回成功发送的字节数,-1 为错误,-2 为 EAGAIN 2023-05-07 13:49:56 +08:00
skywind3000
c0cb6ab3ac 修复流模式相关 buffer 问题 2023-05-07 12:54:02 +08:00
Linwei
10ee2b30c8 Merge pull request #391 from enkiller/dev
Add pykcp to README
2023-04-03 10:15:00 +08:00
tyx
62b38db385 Add pykcp to README 2023-04-02 23:49:22 +08:00
Linwei
fb3ccde6c0 Merge pull request #389 from xboss/master
Add skcp(libev) to README
2023-03-22 08:40:19 +08:00
Jim
b6b86cbb82 Add skcp(libev) to README 2023-03-21 18:15:46 +08:00
Linwei
9bda4ac0b1 Merge pull request #388 from RealistikDash/master
add: `kcp.py` to readme
2023-02-25 11:03:36 +08:00
skywind3000
2c77d64e68 update doc 2023-02-16 08:43:14 +08:00
skywind3000
fe96c9fa8a update doc 2023-02-16 01:57:52 +08:00
skywind3000
5264734c81 update doc 2023-02-16 01:37:00 +08:00
skywind3000
9e662609be update docs 2023-02-15 19:05:51 +08:00
skywind3000
acd7983719 更新用例 2023-02-15 19:03:29 +08:00
RealistikDash
86344664db add: kcp.py to english readme 2023-02-13 17:01:51 +00:00
Linwei
5481f0397f Merge pull request #384 from Homqyy/master
Add open project 'kcp-perl' to README
2022-12-04 13:02:42 +08:00
homqyy
2a80825d37 Add open project 'kcp-perl' to README 2022-12-04 01:03:32 +08:00
Linwei
f482028f24 Merge pull request #380 from myd7349/cmake
improve CMakeLists.txt
2022-11-28 21:27:59 +08:00
myd7349
3c9fd966f9 simplify 2022-11-28 21:24:41 +08:00
myd7349
6900c9128e improve CMakeLists.txt
- upgrade CMake minimal version;
- define three options to give users more control over the build process;
- fix Win32 dynamic build by exporting useful functions;
2022-11-27 20:16:09 +08:00
Linwei
fe306fc4ec Merge pull request #376 from Homqyy/master
同时生成动态库和静态库,安装的时候安装的是动态库
2022-11-16 17:52:22 +08:00
wang_hongqi
d06a81a28a 同时生成动态库和静态库,安装的时候安装的是动态库 2022-11-16 08:16:00 +00:00
Linwei
f553df7afc Merge pull request #343 from b23r0/master
add rust bindings to README
2022-02-01 20:50:51 +08:00
b23r0
db793e8108 add rust bindings to README 2022-02-01 18:08:56 +08:00
Linwei
58139efbba Merge pull request #319 from vis2k/readme_kcp2k
Update README.md: (kcp2k for sharp
2021-06-10 19:55:59 +08:00
vis2k
95dad07646 Update README.md 2021-06-09 21:37:33 +08:00
Linwei
7e8edde201 Merge pull request #317 from Unit-X/master
Add kcp-cpp link to doc
2021-06-05 02:37:46 +08:00
Anders Cedronius
78090be86e Add kcp-cpp link to doc 2021-06-04 14:39:05 +02:00
Linwei
6de8bbf271 Merge pull request #311 from huahang/patch-1
fix: fix new/delete mismatch
2021-04-08 00:14:49 +08:00
huahang
a9feff68b3 fix: fix new/delete mismatch 2021-04-07 11:50:46 +08:00
skywind3000
77a4f85ae6 update docs 2021-01-02 23:26:00 +08:00
skywind3000
e5a9c12ae9 update docs 2021-01-02 23:23:48 +08:00
skywind3000
2ddef54c08 update doc 2021-01-02 23:06:53 +08:00
skywind3000
d4b8fa8709 update docs 2021-01-01 17:44:43 +08:00
skywind3000
57bd697cfc update docs 2021-01-01 17:40:50 +08:00
skywind3000
0ea090bdea update doc 2021-01-01 17:39:02 +08:00
skywind3000
944cbaa411 update doc 2021-01-01 17:34:27 +08:00
Linwei
28c802e6a6 Merge pull request #294 from shaoyuan1943/master
request to add kcp development package with Go
2020-11-09 17:24:12 +08:00
shaoyuan
2fffb01d8b Update README.en.md 2020-11-09 16:42:42 +08:00
shaoyuan
cbb19b76c5 Update README.md 2020-11-09 16:37:23 +08:00
Linwei
d6829263fe Merge pull request #292 from chinsyo/patch-2
Fix typo: 反照 -> 仿照
2020-11-05 18:41:47 +08:00
Chinsyo
5117840a69 Update README.md 2020-11-05 15:22:29 +08:00
Linwei
2163e05b13 Merge pull request #285 from halx99/patch-1
Add yasio kcp integration
2020-10-08 21:38:37 +08:00
HALX99
ff195afe03 Update README.md 2020-09-25 15:52:41 +08:00
HALX99
67ee559e76 Update README.en.md 2020-09-25 15:48:58 +08:00
HALX99
1ca75754cf Update README.md 2020-09-25 15:47:57 +08:00
HALX99
6b9c2b683e Update README.en.md 2020-09-25 15:46:08 +08:00
Linwei
bab2b09391 Merge pull request #283 from shixiongfei/master
fixed: msvc compile warning
2020-09-16 17:49:21 +08:00
shixiongfei
ce02fbd433 fixed: msvc compile warning 2020-09-16 14:27:40 +08:00
Linwei
bf616efb43 Merge pull request #276 from l42111996/master
增加基于dotnetty的csharp版本kcp库
2020-07-23 16:21:29 +08:00
jinmiao
eec3b39516 Update readme 2020-07-23 07:47:27 +08:00
jinmiao
a1ca12aadc Update Readme 2020-07-22 21:56:54 +08:00
请叫我淼哥哥
14c6beb88d Merge pull request #1 from skywind3000/master
update
2020-07-22 21:46:17 +08:00
skywind3000
38e0c9366e take care of strict aliasing 2020-04-24 17:05:43 +08:00
skywind3000
53e568bd3b update testing 2020-03-26 19:37:48 +08:00
skywind3000
700e2a8161 Merge remote-tracking branch 'remotes/origin/master' 2020-03-26 19:29:51 +08:00
skywind3000
9158f84781 update rto calculation 2020-03-26 19:28:17 +08:00
skywind3000
87c0e6a92b update doc 2020-02-24 03:36:27 +08:00
skywind3000
cdf138f45b update doc 2020-02-24 03:29:35 +08:00
skywind3000
9c4d000811 update doc 2020-02-24 03:27:32 +08:00
skywind3000
cbf46fa1e9 fixed: window recovery is unefficient (by @dearplain) 2020-02-23 00:04:57 +08:00
skywind3000
d003f99119 fixed: window recovery is unefficient (by @dearplain) 2020-02-22 23:59:10 +08:00
skywind3000
44986d37d8 Merge branch 'master' of https://github.com/skywind3000/kcp 2020-01-21 21:43:32 +08:00
skywind3000
cf683713cb fixed: incorrect log channel 2020-01-20 16:24:16 +08:00
Linwei
5cdea1eea0 Merge pull request #250 from JackBoosY/dev/jack/fix_typo
fix typo in readme
2020-01-16 18:04:56 +08:00
JackBoosY
62a0cc1418 fix typo 2020-01-16 01:50:14 -08:00
Linwei
d43e88147d Merge pull request #249 from JackBoosY/vcpkg-instructions
Add vcpkg installation instructions
2020-01-16 16:27:44 +08:00
JackBoosY
cd8c0da05f Fix typo 2020-01-16 00:17:36 -08:00
JackBoosY
2acf5a39c7 Add vcpkg installation instructions 2020-01-16 00:13:44 -08:00
skywind3000
c87144969e update 2020-01-11 00:38:53 +08:00
skywind3000
6bd25130cb update 2020-01-11 00:37:24 +08:00
skywind3000
bfc2e502df update 2020-01-11 00:36:05 +08:00
skywind3000
6514e149c5 update doc 2020-01-08 16:03:30 +08:00
skywind3000
25e809ad42 commit new README.md 2020-01-08 16:02:17 +08:00
skywind3000
73dfc248cf update README.md 2020-01-08 15:55:29 +08:00
skywind3000
474b36b844 polish doc 2020-01-08 02:44:50 +08:00
skywind3000
408fe80908 update doc 2020-01-08 02:40:06 +08:00
Linwei
d86e7091b0 Merge pull request #234 from simdsoft/master
fix warnings.
2019-11-12 15:03:03 +08:00
halx99
e47e22b583 fix warnings. 2019-11-11 21:53:04 +08:00
Linwei
4c58607c91 Merge pull request #228 from myd7349/cmakelists-improvement 2019-09-21 16:22:19 +08:00
myd7349
6256055924 improve CMakeLists.txt
- add install target
- add BUILD_TESTING option
2019-09-21 15:06:58 +08:00
skywind3000
362c49d590 new twitter 2019-08-20 14:57:03 +08:00
skywind3000
0d6a958076 update documents 2019-08-12 15:56:50 +08:00
skywind3000
234239b9e2 Merge branch 'master' of https://github.com/skywind3000/kcp 2019-08-06 21:30:49 +08:00
skywind3000
79b21e78e1 update doc 2019-08-05 21:22:19 +08:00
skywind3000
32a470763c commit new doc 2019-08-05 17:49:53 +08:00
skywind3000
beb4563891 update doc 2019-08-05 17:48:22 +08:00
skywind3000
5fdf5173f9 commit new README.md 2019-08-05 17:45:16 +08:00
skywind3000
ceedae3c32 update docs 2019-08-05 17:43:36 +08:00
skywind3000
fad7565d6f update doc 2019-08-05 16:58:59 +08:00
skywind3000
a5d82ca1cb new: IKCP_FASTACK_LIMIT 2019-08-05 16:56:32 +08:00
skywind3000
3a9196b1b7 new: IKCP_FASTACK_CONSERVE 2019-08-05 16:13:56 +08:00
Linwei
1a3773881a Merge pull request #220 from l42111996/master
新增案例
2019-08-05 14:04:47 +08:00
jinmiao
abb5f2edbf 新增案例 2019-08-05 11:37:54 +08:00
skywind3000
a4b6748cb5 new: meet armv7 bus alignment requirements
fixed: ambiguous variable names.
2019-07-23 14:20:31 +08:00
skywind3000
384a913339 Merge branch 'master' of https://github.com/skywind3000/kcp 2019-06-19 22:44:18 +08:00
skywind3000
19dbf3af05 remove warnings 2019-06-19 20:40:25 +08:00
skywind3000
4b8ae65e26 Merge branch 'master' of https://github.com/skywind3000/kcp 2019-05-09 15:48:50 +08:00
skywind3000
7c4a592b56 commit new benchmark.png 2019-05-09 15:48:08 +08:00
Linwei
726b0d0ce9 Merge pull request #200 from raymonwang/master
add CMakeList.txt to compile static lib for kcp
2019-04-29 22:21:59 +08:00
raymonwang
e7545240ea add CMakeList.txt to compile static lib for kcp 2019-04-29 07:24:39 +08:00
skywind3000
c8a2f452f4 增加:HP-Socket 案例 2019-04-28 16:03:14 +08:00
skywind3000
cdee01cd04 update doc 2019-02-27 16:28:57 +08:00
skywind3000
efe569bfa7 update doc 2019-02-27 16:02:26 +08:00
Linwei
5996b73206 Merge pull request #191 from KumoKyaku/master
添加一个新版本csharp移植链接。
2019-02-23 18:15:07 +08:00
云却
1db6af36c3 添加一个新版本csharp移植链接。 2019-02-23 16:01:18 +09:00
Linwei
21a7a17263 Merge pull request #189 from opencollective/opencollective
Activating Open Collective
2019-02-04 01:20:14 +08:00
Jess
113a6b61d0 Added backers and sponsors on the README 2019-02-03 09:15:01 -08:00
skywind3000
682060e012 update doc 2018-12-06 15:20:18 +08:00
Linwei
2df2110e6a Merge pull request #177 from junliangtan/master
fixed the crash issue when len is minus caused by invalid data.
2018-11-02 04:29:15 +08:00
tanjunliang
3580539e0f fixed the crash issue when len is minus caused by invalid data. 2018-11-01 10:26:54 +08:00
skywind3000
b8100f9de9 update gitter group 2018-05-24 12:09:56 +08:00
skywind3000
6bd172c48d change hardcode number to const 2018-03-24 13:47:57 +08:00
skywind3000
a964c01fa6 fixed: https://github.com/skywind3000/kcp/issues/140 2018-03-24 13:37:48 +08:00
skywind3000
cbf95831f9 Merge branch 'master' of https://github.com/skywind3000/kcp 2018-03-15 22:35:19 +08:00
skywind3000
5c5108a612 update protocol specification 2018-03-15 22:34:59 +08:00
Linwei
8407e6d8a0 Merge pull request #135 from szhnet/master
添加kcp-netty到开源案例
2018-02-01 15:18:05 +08:00
szh
23d8e61d2e 添加kcp-netty到开源案例 2018-02-01 14:54:01 +08:00
Linwei
29ecf30666 Merge pull request #130 from oyyd/add-related-apps
添加nysocks到相关应用
2018-01-08 20:28:40 +08:00
oyyd
27ba6e63ac 添加nysocks到相关应用 2018-01-08 19:18:24 +08:00
Linwei
110f9b19da Merge pull request #125 from egametang/master
readme增加et-frame的kcp链接
2017-12-12 16:36:53 +08:00
tanghai
2aa44a631d readme增加et-frame的kcp链接 2017-12-12 16:25:43 +08:00
skywind3000
d104728e3a Merge branch 'master' of https://github.com/skywind3000/kcp 2017-08-28 16:43:28 +08:00
skywind3000
5eef03ed71 更新 xkcptun: C 语言实现的kcptun客户端 2017-08-28 16:43:13 +08:00
Linwei
9f86f27f8b Merge pull request #99 from liuxuzzz/master
删除README.md中“协议模式”-“工作模式”-“普通模式”中多余的一个反引号。
2017-08-28 16:35:15 +08:00
liuxuzzz
63ac667e21 README.md删除“协议模式”-“工作模式”-“普通模式”中多余的一个反引号。 2017-08-28 13:38:11 +08:00
Linwei
b1c300a101 Merge pull request #97 from losfair/master
Fix typo in IWORDS_BIG_ENDIAN macro definition
2017-08-20 15:58:32 +08:00
losfair
a6f720f03e Fix typo in IWORDS_BIG_ENDIAN macro definition 2017-08-19 11:17:51 +08:00
skywind3000
739dcacb45 add new libraries 2017-07-21 14:54:27 +08:00
skywind3000
36c5a368de remove unused code, remove warning 2017-06-13 22:52:36 +08:00
skywind3000
6093e928bd new readme 2017-06-08 21:26:43 +08:00
skywind3000
efd1c7eee2 new readme in english 2017-06-08 21:25:55 +08:00
skywind3000
b0ef38b104 new readme 2017-06-08 21:24:56 +08:00
skywind3000
9cb6dce5f6 更新文档 2017-06-08 15:25:54 +08:00
skywind3000
e89c173c50 优化文档 2017-06-08 15:23:45 +08:00
skywind3000
1f83287d1e 添加商业案例 2017-06-08 15:16:12 +08:00
skywind3000
c129925f64 Merge branch 'master' of https://github.com/skywind3000/kcp
# Conflicts:
#	README.md
2017-06-08 00:07:25 +08:00
skywind3000
22b117e841 增加成功案例 2017-06-08 00:05:28 +08:00
Linwei
7f8459e6db Merge pull request #74 from boliou/master
修正 README 中格式错误
2017-04-26 13:14:20 +08:00
Bo Liou
63a5584202 Update README.en.md 2017-04-26 12:38:16 +08:00
Bo Liou
2d4a604e34 Update README.md 2017-04-26 12:37:49 +08:00
Linwei
09c0d67808 Merge pull request #72 from liudf0716/kcp-xkcptun
添加xkcptun到相关应用中
2017-04-17 15:14:17 +08:00
Dengfeng Liu
93b1ce2ea1 添加xkcptun到相关应用中
c语言实现的kcp tune,主要用于openwrt, LEDE开发的路由器项目上
2017-04-17 11:06:33 +08:00
Linwei
5fcf575218 Merge pull request #61 from xtaci/master
change clock granularity(G) to kcp->interval
2017-02-16 13:15:51 +08:00
xtaci
34d75bcda6 change clock granularity(G) to kcp->interval 2017-02-05 15:08:46 +08:00
Linwei
f481c9ce4e Merge pull request #59 from QXSoftware/feature/fix-testcase-encoding
使用 utf8-without-bom 编码,否则使用 Sublime Text 打开注释显示乱码
2017-02-02 19:29:05 +08:00
Linwei
6b81e04bfa Merge pull request #58 from QXSoftware/feature/fix-magic-number
使用宏定义而不是 magic number
2017-02-02 19:27:18 +08:00
xiaocheng
9ceb65a664 使用宏定义而不是 magic number 2017-02-02 12:10:00 +08:00
xiaocheng
8a61662d1c 使用 utf8-without-bom 编码,否则使用 sublime 打开注释显示乱码 2017-02-02 12:07:40 +08:00
skywind3000
1cd5683bb2 new document 2017-01-16 13:02:02 +08:00
skywind3000
194b03c404 new readme 2017-01-16 12:59:16 +08:00
skywind3000
03676ee3ba update document 2017-01-15 03:32:46 +08:00
skywind3000
d0a23ac8fe update documents 2017-01-13 19:19:54 +08:00
skywind3000
6ffd0bb6c9 change LICENSE from GPL to MIT 2017-01-13 19:12:31 +08:00
skywind3000
ff571b6844 update document 2017-01-13 17:52:06 +08:00
skywind3000
dd5337579a new english document 2017-01-13 17:46:29 +08:00
skywind3000
f74accebc2 new README.md 2016-11-23 22:49:54 +08:00
skywind3000
3befca7f98 cut long lines to short lines within 78 characters, add ikcp_getconv 2016-09-12 12:23:14 +08:00
Linwei
e2812af1e5 Merge pull request #40 from U2FsdGVkX1/master
新增ikcp_setoutput函数
2016-09-12 12:16:56 +08:00
U2FsdGVkX1
abf9ce1464 新增ikcp_setoutput函数 2016-09-10 20:02:36 +08:00
skywind3000
8813e65158 update document 2016-08-16 13:04:30 +08:00
skywind3000
56665a7d51 update document 2016-08-16 12:55:30 +08:00
skywind3000
c0f5daffc8 update doc: add references to new projects which is using kcp 2016-08-16 12:53:31 +08:00
skywind3000
0cdfb61941 optimize ikcp_send for stream mode 2016-07-26 11:27:13 +08:00
skywind3000
f14622a495 add stream mode 2016-07-25 20:04:17 +08:00
skywind3000
478275193b update README.md 2016-07-22 19:58:22 +08:00
skywind3000
cbd072ef55 add travis 2016-07-20 16:33:53 +08:00
skywind3000
c38025f0be fixed travis script 2016-07-20 16:26:05 +08:00
skywind3000
6d2dc91f1f fixed build issue 2016-07-20 16:22:13 +08:00
skywind3000
0df053a996 new travis.yml 2016-07-20 16:17:03 +08:00
skywind3000
c84ed70529 update document, 2016-07-20 09:27:23 +08:00
skywind3000
2d7df06adb remove icon 2016-07-17 23:22:55 +08:00
skywind3000
d75caa531b update kcp powered icon 2016-07-15 19:50:46 +08:00
skywind3000
eb4eae10d8 revert 2016-07-14 01:17:54 +08:00
skywind3000
bf4cc82998 reserved identifier to fit secure coding 2016-07-14 01:09:20 +08:00
skywind3000
45f2fd6056 new kcp power svg 2016-07-04 18:42:15 +08:00
skywind3000
96c0c69c5e new testing 2016-06-03 20:33:41 +08:00
skywind3000
3806c95073 improve performance & optimize fast-ack 2016-06-03 20:28:21 +08:00
Linwei
aec1aa6ef1 Merge pull request #20 from xtaci/master
修改deadlink的默认值为 20
2016-05-06 21:50:19 +08:00
Daniel Fu
812b4fdb12 Update ikcp.c 2016-05-06 18:20:54 +08:00
skywind3000
3a9ebccdab fixed warning in latest c++ compilers 2016-05-06 10:27:12 +08:00
Linwei
5608f9df87 Merge pull request #16 from gyf19/master
retrun error code
2016-04-21 20:50:26 +08:00
gyf19
1afffd763d retrun error code 2016-04-21 20:39:32 +08:00
Linwei
0ce0ecf567 Update README.md 2016-04-21 19:44:57 +08:00
Linwei
3539421556 Merge pull request #15 from xtaci/master
Update README.md
2016-04-21 19:43:40 +08:00
Daniel Fu
cc58efa2b7 Update README.md 2016-04-21 17:50:03 +08:00
skywind3000
a05a5569d7 update doc 2016-03-28 21:48:58 +08:00
skywind3000
cf53102b8f udpate doc 2016-03-14 17:39:21 +08:00
skywind3000
cdb6dd2d2c udpate doc 2016-03-14 17:37:10 +08:00
skywind3000
722fad30d2 udpate doc 2016-03-14 17:35:15 +08:00
skywind3000
3bb0342cda udpate doc 2016-03-14 17:31:32 +08:00
skywind3000
7cc422be7c udpate doc 2016-03-14 17:27:58 +08:00
skywind3000
4a3f8867bc udpate doc 2016-03-14 17:27:09 +08:00
skywind3000
465ac05f9f udpate doc 2016-03-14 17:26:18 +08:00
skywind3000
b08f757cd1 udpate doc 2016-03-14 17:24:46 +08:00
skywind3000
623e63bb88 update readme 2016-03-02 14:59:15 +08:00
skywind3000
53d9faa0ba commit new readme 2016-02-25 23:16:58 +08:00
skywind3000
b2c938f641 update doc 2016-02-25 15:36:43 +08:00
skywind3000
9ffb0967fd new document 2016-02-25 15:29:36 +08:00
skywind3000
4798ecabe9 update sample 2016-02-25 15:13:11 +08:00
skywind3000
43eb92a4b5 thanks donation 2016-02-23 11:14:26 +08:00
skywind3000
068e714c58 update: thanks for donation 2016-02-23 11:13:13 +08:00
skywind3000
7e79edf08d update doc 2016-02-19 16:05:12 +08:00
skywind3000
23a8bda708 update documents 2016-02-19 15:55:40 +08:00
skywind3000
d757d5ab4c 更新文档 2016-02-19 11:18:53 +08:00
skywind3000
8d52129c60 update document 2016-02-18 22:26:05 +08:00
skywind3000
9d641e9633 update document 2016-02-18 22:15:54 +08:00
skywind3000
43ea3cb7f3 add asio-kcp 2016-02-18 22:12:54 +08:00
skywind3000
12fa3780f0 update README.md 2015-12-25 10:48:48 +08:00
skywind3000
1e29e4f20e commit new README.md 2015-12-25 10:48:00 +08:00
16 changed files with 1220 additions and 638 deletions

69
.gitignore vendored Normal file
View File

@@ -0,0 +1,69 @@
*
!*/
!*.*
*.obj
*.o
*.lib
*.ipch
*.pch
*.sdf
*.exe
*.a
*.p
*.dll
*.so
*.sdf
.tasks
.root
__pycache__
/build/*
/example/build/*
/gateway/build/*
/.vscode/*
/.vs/*
/.cache/*
/testing/*.xlsx
/testing/*.txt
/update.cmd
.vs
/visualstudio/Debug/*
/visualstudio/Release/*
/visualstudio/x64/*
/visualstudio/bbnet/*
/visualstudio/.vs/*
/visualstudio/bbnet.vcxproj.user
/x64/*
/Debug/*
/Release/*
/bbnet/*
*.vcxproj.user
/update.cmd
*.pcap
*.win32
*.linux
*.linux2
*.log
*.pyc
*.pyo
*.pyd
__pycache__/*
/session*.md
/skills/*
/.qoder/*
/.opencode/*
/.claude/*
/.iflow/*
nul

9
.travis.yml Normal file
View File

@@ -0,0 +1,9 @@
language: cpp
compiler:
- gcc
- clang
script:
- $CC -O3 test.cpp -o test -lstdc++

62
CMakeLists.txt Normal file
View File

@@ -0,0 +1,62 @@
CMAKE_MINIMUM_REQUIRED(VERSION 4.0)
project(kcp LANGUAGES C)
include(CTest)
include(GNUInstallDirs)
cmake_policy(SET CMP0054 NEW)
if(BUILD_SHARED_LIBS AND WIN32)
set(exports_def_file "${CMAKE_CURRENT_BINARY_DIR}/exports.def")
set(exports_def_contents
"EXPORTS
ikcp_create
ikcp_release
ikcp_setoutput
ikcp_recv
ikcp_send
ikcp_update
ikcp_check
ikcp_input
ikcp_flush
ikcp_peeksize
ikcp_setmtu
ikcp_wndsize
ikcp_waitsnd
ikcp_nodelay
ikcp_log
ikcp_allocator
ikcp_getconv
")
file(WRITE "${exports_def_file}" "${exports_def_contents}")
add_library(kcp ikcp.c "${exports_def_file}")
else()
add_library(kcp ikcp.c)
endif()
install(FILES ikcp.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
install(TARGETS kcp
EXPORT kcp-targets
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
)
install(EXPORT kcp-targets
FILE kcp-config.cmake
NAMESPACE kcp::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/kcp
)
if(BUILD_TESTING)
enable_language(CXX)
add_executable(kcp_test test.cpp)
if(MSVC AND NOT (MSVC_VERSION LESS 1900))
target_compile_options(kcp_test PRIVATE /utf-8)
endif()
endif()

353
LICENSE
View File

@@ -1,340 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
MIT License
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyright (c) 2017 Lin Wei (skywind3000 at gmail.com)
Preamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

248
README.en.md Normal file
View File

@@ -0,0 +1,248 @@
KCP - A Fast and Reliable ARQ Protocol
======================================
[![Powered][3]][1]
[![GitHub license][6]][7]
[![Backers on Open Collective](https://opencollective.com/kcp/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/kcp/sponsors/badge.svg)](#sponsors)
[1]: https://github.com/skywind3000/kcp
[2]: https://github.com/skywind3000/kcp/raw/master/kcp.svg
[3]: https://github.com/skywind3000/kcp/raw/master/kcp.svg
[4]: https://api.travis-ci.org/skywind3000/kcp.svg?branch=master
[5]: https://travis-ci.org/skywind3000/kcp
[6]: https://img.shields.io/badge/license-MIT-blue.svg
[7]: https://github.com/skywind3000/kcp/blob/master/LICENSE
# Introduction
**KCP** is a high-performance, reliable transport protocol designed to significantly reduce latency compared to traditional TCP. It can achieve a **3040% reduction in average latency** and up to three times lower maximum delay, _costing 1020% additional bandwidth overhead_.
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.
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.
# Technical Specifications
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 1020% more bandwidth overhead for 3040% faster transmission speed compared to TCP.
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.
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:
#### RTO Doubled vs Not Doubled:
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.
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.
#### Selective Retransmission vs Full Retransmission:
TCP often retransmits all subsequent data after a lost packet, which can lead to excessive redundancy.
KCP implements selective retransmission, ensuring that only the actually lost packets are resent, minimizing unnecessary data transmission and improving efficiency.
#### Fast Retransmission:
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.
#### Delayed ACK vs Non-delayed ACK:
TCP often delays ACKs to optimize throughput, which can unintentionally inflate RTT calculations and delay loss detection—even with `NODELAY` settings.
KCP provides configurable ACK behavior, allowing ACKs to be sent immediately when needed, enhancing responsiveness in latency-sensitive applications.
#### UNA vs ACK+UNA
ARQ protocols typically use either:
UNA (Unacknowledged Acknowledgment): Confirms all packets before a given sequence number (e.g., TCP).
ACK: Confirms receipt of a specific packet.
Each has tradeoffs: UNA can lead to full retransmissions, and standalone ACKs create overhead during loss.
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.
#### Non-concessional Flow Control:
By default, KCP follows TCP's fair flow control—factoring in send buffer size, receiver buffer, congestion control, and slow-start.
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.
# Quick Install
You can download and install kcp using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install kcp
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.
# Basic Usage
1. Create KCP object:
```cpp
// Initialize the kcp object, conv is an integer that represents the session number,
// same as the conv of tcp, both communication sides shall ensure the same conv,
// so that mutual data packets can be recognized, user is a pointer which will be
// passed to the callback function.
ikcpcb *kcp = ikcp_create(conv, user);
```
2. Set the callback function:
```cpp
// KCP lower layer protocol output function, which will be called by KCP when it
// needs to send data, buf/len represents the buffer and data length.
// user refers to the incoming value at the time the kcp object is created to
// distinguish between multiple KCP objects
int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
....
}
// Set the callback function
kcp->output = udp_output;
```
3. Call update in an interval:
```cpp
// Call ikcp_update at a certain frequency to update the kcp state, and pass in
// the current clock (in milliseconds). If the call is executed every 10ms, or
// ikcp_check is used to determine time of the next call for update, no need to
// call every time;
ikcp_update(kcp, millisec);
```
4. Input a lower layer data packet:
```cpp
// Need to call when a lower layer data packet (such as UDP packet)is received:
ikcp_input(kcp, received_udp_packet, received_udp_size);
```
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.
# Protocol Configuration
The protocol default mode is a standard ARQ, and various acceleration switches can be enabled by configuration:
1. Working Mode:
```cpp
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
```
- `nodelay`: Whether nodelay mode is enabled, 0 is not enabled; 1 enabled.
- `interval` P rotocol internal work interval, in milliseconds, such as 10 ms or 20 ms.
- `resend` Fast retransmission mode, 0 represents off by default, 2 can be set (2 ACK spans will result in direct retransmission)
- `nc` Whether to turn off flow control, 0 represents “Do not turn off” by default, 1 represents “Turn off”.
- Normal Mode: ikcp_nodelay(kcp, 0, 40, 0, 0);
- Turbo Mode ikcp_nodelay(kcp, 1, 10, 2, 1);
2. Window Size:
```cpp
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);
```
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.
3. Maximum Transmission Unit:
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.
4. Minimum RTO:
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:
```cpp
kcp->rx_minrto = 10;
```
# Document Indexing
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:
- [KCP Best Practice](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice-EN)
- [Integration with the Existing TCP Server](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice-EN)
- [Benchmarks](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark)
# Related Applications
- [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.
- [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.
- [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.
- [HP-Socket](https://github.com/ldcsaa/HP-Socket): High Performance TCP/UDP/HTTP Communication Component.
- [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.
- [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.
- [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.
- [kcp-perl](https://github.com/Homqyy/kcp-perl): Perl extensions for kcp. It's OOP and Perl-Like.
- [kcp-java](https://github.com/hkspirt/kcp-java)Implementation of Java version of KCP protocol.
- [kcp-netty](https://github.com/szhnet/kcp-netty)Java implementation of KCP based on Netty.
- [java-kcp](https://github.com/l42111996/java-Kcp): JAVA version KCP, based on netty implementation (including fec function)
- [kcp.kt](https://github.com/jokelbaf/kcp.kt): A pure-Kotlin Multiplatform implementation of KCP. Supports JVM, Linux, Windows, macOS and iOS targets.
- [csharp-kcp](https://github.com/l42111996/csharp-kcp): csharp version KCP, based on dotNetty implementation (including fec function)
- [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.
- [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.
- [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.
- [Kcp-CSharp](https://github.com/Molth/Kcp-CSharp): a pure C# KCP instance callback(delegate) wrapper for (Unity/Godot/.NET)
- [kcp2k](https://github.com/vis2k/kcp2k/): Line-by-line translation to C#, with optional Server/Client on top.
- [KcpSharpN](https://github.com/new1271/KcpSharpN): The csharp version of KCP, translated from the original C code, includes a simple wrapper of the protocol for easy use, but also allows calling the functions of the KCP protocol directly (just like C code)
- [kcp-rs](https://github.com/en/kcp-rs): The rust migration of KCP
- [kcp-rust-native](https://github.com/b23r0/kcp-rust-native)KCP bindings for Rust
- [lua-kcp](https://github.com/linxiaolong/lua-kcp): Lua extension of KCP, applicable for Lua server
- [node-kcp](https://github.com/leenjewel/node-kcp): KCP interface for node-js
- [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.
- [shadowsocks-android](https://github.com/shadowsocks/shadowsocks-android): Shadowsocks for android has integrated kcptun using kcp protocol to accelerate shadowsocks, with good results
- [kcpuv](https://github.com/elisaday/kcpuv): The kcpuv library developed with libuv, currently still in the early alpha phase.
- [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.
- [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).
- [gouxp](https://github.com/shaoyuan1943/gouxp): Implementing a callback-based KCP development package with Go, with decryption and FEC support, is easy to use.
- [kcp.py](https://github.com/RealistikDash/kcp.py): Python bindings and networking with an emphasis on dev friendliness.
- [pykcp](https://github.com/enkiller/pykcp): KCP implementation for Python version.
- [php-ext-kcp](https://github.com/wpjscc/php-ext-kcp): php extension for KCP.
- [asio-kcp(new)](https://github.com/sniper00/asio-kcp): KCP implementation for C++/Asio, with Modern C++/Asio async features, such as coroutine.
# Protocol Comparison
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.
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:
- ASIO-KCP **has good performace in wifi and phone network(3G, 4G)**.
- The kcp is the **first choice for realtime pvp game**.
- The lag is less than 1 second when network lag happen. **3 times better than enet** when lag happen.
- The enet is a good choice if your game allow 2 second lag.
- **UDT is a bad idea**. It always sink into badly situation of more than serval seconds lag. And the recovery is not expected.
- enet has the problem of lack of doc. And it has lots of functions that you may intrest.
- 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.
- The kcp is a simple thing. You will write more code if you want more feature.
- UDT has a perfect doc. UDT may has more bug than others as I feeling.
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.
MMO Engine [SpatialOS](https://improbable.io/spatialOS) has a benchmark report on KCP/TCP/RakNet:
![](images/spatialos-50.png)
for more details, please see the report itself:
- [Kcp a new low latency secure network stack](https://improbable.io/blog/kcp-a-new-low-latency-secure-network-stack)
# KCP is used by
See [Success Stories](https://github.com/skywind3000/kcp/wiki/Success-Stories).
# Donation
![欢迎使用支付宝对该项目进行捐赠](https://raw.githubusercontent.com/skywind3000/kcp/master/images/donation.png)
Donation is welcome by using alipay, the money will be used to improve the protocol and documentation.
twitter: https://twitter.com/skywind3000
blog: http://www.skywind.me
zhihu: https://www.zhihu.com/people/skywind3000

418
README.md
View File

@@ -1,139 +1,291 @@
KCP - A Fast and Reliable ARQ Protocol
======================================
# 简介
KCP是一个快速可靠协议能以比 TCP浪费10%-20%的带宽的代价,换取平均延迟降低 30%-40%且最大延迟降低三倍的传输效果。纯算法实现并不负责底层协议如UDP的收发需要使用者自己定义下层数据包的发送方式以 callback的方式提供给 KCP。 连时钟都需要外部传递进来,内部不会有任何一次系统调用。
整个协议只有 ikcp.h, ikcp.c两个源文件可以方便的集成到用户自己的协议栈中。也许你实现了一个P2P或者某个基于 UDP的协议而缺乏一套完善的ARQ可靠协议实现那么简单的拷贝这两个文件到现有项目中稍微编写两行代码即可使用。
# 技术特性
TCP是为流量设计的每秒内可以传输多少KB的数据讲究的是充分利用带宽。而 KCP是为流速设计的单个数据包从一端发送到一端需要多少时间以10%-20%带宽浪费的代价换取了比 TCP快30%-40%的传输速度。TCP信道是一条流速很慢但每秒流量很大的大运河而KCP是水流湍急的小激流。KCP有正常模式和快速模式两种通过以下策略达到提高流速的结果
#### RTO翻倍vs不翻倍
TCP超时计算是RTOx2这样连续丢三次包就变成RTOx8了十分恐怖而KCP启动快速模式后不x2只是x1.5实验证明1.5这个值相对比较好),提高了传输速度。
#### 选择性重传 vs 全部重传:
TCP丢包时会全部重传从丢的那个包开始以后的数据KCP是选择性重传只重传真正丢失的数据包
#### 快速重传:
发送端发送了1,2,3,4,5几个包然后收到远端的ACK: 1, 3, 4, 5当收到ACK3时KCP知道2被跳过1次收到ACK4时知道2被跳过了2次此时可以认为2号丢失不用等超时直接重传2号包大大改善了丢包时的传输速度。
#### 延迟ACK vs 非延迟ACK
TCP为了充分利用带宽延迟发送ACKNODELAY都没用这样超时计算会算出较大 RTT时间延长了丢包时的判断过程。KCP的ACK是否延迟发送可以调节。
#### UNA vs ACK+UNA
ARQ模型响应有两种UNA此编号前所有包已收到如TCP和ACK该编号包已收到光用UNA将导致全部重传光用ACK则丢失成本太高以往协议都是二选其一而 KCP协议中除去单独的 ACK包外所有包都有UNA信息。
#### 非退让流控:
KCP正常模式同TCP一样使用公平退让法则即发送窗口大小由发送缓存大小、接收端剩余接收缓存大小、丢包退让及慢启动这四要素决定。但传送及时性要求很高的小数据时可选择通过配置跳过后两步仅用前两项来控制发送频率。以牺牲部分公平性及带宽利用率之代价换取了开着BT都能流畅传输的效果。
# 基本使用
1. 创建 KCP对象
```cpp
// 初始化 kcp对象conv为一个表示会话编号的整数和tcp的 conv一样通信双
// 方需保证 conv相同相互的数据包才能够被认可user是一个给回调函数的指针
ikcpcb *kcp = ikcp_create(conv, user);
```
2. 设置回调函数:
```cpp
// KCP的下层协议输出函数KCP需要发送数据时会调用它
// buf/len 表示缓存和长度
// user指针为 kcp对象创建时传入的值用于区别多个 KCP对象
int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
....
}
// 设置回调函数
kcp->output = udp_output;
```
3. 循环调用 update
```cpp
// 以一定频率调用 ikcp_update来更新 kcp状态并且传入当前时钟毫秒单位
// 如 10ms调用一次或用 ikcp_check确定下次调用 update的时间不必每次调用
ikcp_update(kcp, millisec);
```
4. 输入一个下层数据包:
```cpp
// 收到一个下层数据包比如UDP包时需要调用
ikcp_input(kcp, received_udp_packet, received_udp_size);
```
处理了下层协议的输出/输入后 KCP协议就可以正常工作了使用 ikcp_send 来向
远端发送数据。而另一端使用 ikcp_recv(kcp, ptr, size)来接收数据。
# 协议配置
协议默认模式是一个标准的 ARQ需要通过配置打开各项加速开关
1. 工作模式:
```cpp
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
```
> nodelay :是否启用 nodelay模式0不启用1启用。
> interval :协议内部工作的 interval单位毫秒比如 10ms或者 20ms
> resend 快速重传模式默认0关闭可以设置22次ACK跨越将会直接重传
> nc 是否关闭流控默认是0代表不关闭1代表关闭。
> 普通模式:`ikcp_nodelay(kcp, 0, 40, 0, 0);
> 极速模式: ikcp_nodelay(kcp, 1, 10, 2, 1);
2. 最大窗口:
```cpp
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);
```
该调用将会设置协议的最大发送窗口和最大接收窗口大小默认为32. 这个可以理解为 TCP的 SND_BUF 和 RCV_BUF只不过单位不一样 SND/RCV_BUF 单位是字节,这个单位是包。
3. 最大传输单元
纯算法协议并不负责探测 MTU默认 mtu是1400字节可以使用ikcp_setmtu来设置该值。该值将会影响数据包归并及分片时候的最大传输单元。
4. 最小RTO
不管是 TCP还是 KCP计算 RTO时都有最小 RTO的限制即便计算出来RTO为40ms由于默认的 RTO是100ms协议只有在100ms后才能检测到丢包快速模式下为30ms可以手动更改该值
```cpp
kcp->rx_minrto = 10;
```
# 更多内容
协议的使用和配置都是很简单的,大部分情况看完上面的内容基本可以使用了。如果你需要进一步进行精细的控制,比如改变 KCP的内存分配器或者你需要更有效的大规模调度 KCP链接比如 3500个以上或者如何更好的同 TCP结合那么可以继续延伸阅读
KCP - A Fast and Reliable ARQ Protocol
======================================
[![Powered][3]][1]
[![GitHub license][6]][7]
[![Backers on Open Collective](https://opencollective.com/kcp/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/kcp/sponsors/badge.svg)](#sponsors)
[1]: https://github.com/skywind3000/kcp
[2]: https://github.com/skywind3000/kcp/raw/master/kcp.svg
[3]: https://github.com/skywind3000/kcp/raw/master/kcp.svg
[4]: https://api.travis-ci.org/skywind3000/kcp.svg?branch=master
[5]: https://travis-ci.org/skywind3000/kcp
[6]: https://img.shields.io/badge/license-MIT-blue.svg
[7]: https://github.com/skywind3000/kcp/blob/master/LICENSE
[README in English](https://github.com/skywind3000/kcp/blob/master/README.en.md)
# 简介
KCP是一个快速可靠协议能以比 TCP 浪费 10%-20% 的带宽的代价,换取平均延迟降低 30%-40%且最大延迟降低三倍的传输效果。纯算法实现并不负责底层协议如UDP的收发需要使用者自己定义下层数据包的发送方式以 callback的方式提供给 KCP。 连时钟都需要外部传递进来,内部不会有任何一次系统调用
整个协议只有 ikcp.h, ikcp.c两个源文件可以方便的集成到用户自己的协议栈中。也许你实现了一个P2P或者某个基于 UDP的协议而缺乏一套完善的ARQ可靠协议实现那么简单的拷贝这两个文件到现有项目中稍微编写两行代码即可使用。
**注意KCP 目前更新到 V2增加了可插拔的流控算法机制可以不改协议的情况下替换流控算法老的 v1 足够稳定,我放到了 v1 这个 branch 里。**
# 技术特性
TCP是为流量设计的每秒内可以传输多少KB的数据讲究的是充分利用带宽。而 KCP是为流速设计的单个数据包从一端发送到一端需要多少时间以10%-20%带宽浪费的代价换取了比 TCP快30%-40%的传输速度。TCP信道是一条流速很慢但每秒流量很大的大运河而KCP是水流湍急的小激流。KCP有正常模式和快速模式两种通过以下策略达到提高流速的结果
#### RTO翻倍vs不翻倍
TCP超时计算是RTOx2这样连续丢三次包就变成RTOx8了十分恐怖而KCP启动快速模式后不x2只是x1.5实验证明1.5这个值相对比较好),提高了传输速度。
#### 选择性重传 vs 全部重传:
TCP丢包时会全部重传从丢的那个包开始以后的数据KCP是选择性重传只重传真正丢失的数据包。
#### 快速重传:
发送端发送了1,2,3,4,5几个包然后收到远端的ACK: 1, 3, 4, 5当收到ACK3时KCP知道2被跳过1次收到ACK4时知道2被跳过了2次此时可以认为2号丢失不用等超时直接重传2号包大大改善了丢包时的传输速度。
#### 延迟ACK vs 非延迟ACK
TCP为了充分利用带宽延迟发送ACKNODELAY都没用这样超时计算会算出较大 RTT时间延长了丢包时的判断过程。KCP的ACK是否延迟发送可以调节。
#### UNA vs ACK+UNA
ARQ模型响应有两种UNA此编号前所有包已收到如TCP和ACK该编号包已收到光用UNA将导致全部重传光用ACK则丢失成本太高以往协议都是二选其一而 KCP协议中除去单独的 ACK包外所有包都有UNA信息。
#### 非退让流控:
KCP正常模式同TCP一样使用公平退让法则即发送窗口大小由发送缓存大小、接收端剩余接收缓存大小、丢包退让及慢启动这四要素决定。但传送及时性要求很高的小数据时可选择通过配置跳过后两步仅用前两项来控制发送频率。以牺牲部分公平性及带宽利用率之代价换取了开着BT都能流畅传输的效果。
# 快速安装
您可以使用[vcpkg](https://github.com/Microsoft/vcpkg)库管理器下载并安装kcp:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install kcp
vcpkg中的kcp库由Microsoft团队成员和社区贡献者保持最新状态。如果版本过时请在vcpkg存储库上[创建issue或提出PR](https://github.com/Microsoft/vcpkg)。
# 基本使用
1. 创建 KCP对象
```cpp
// 初始化 kcp对象conv为一个表示会话编号的整数和tcp的 conv一样通信双
// 方需保证 conv相同相互的数据包才能够被认可user是一个给回调函数的指针
ikcpcb *kcp = ikcp_create(conv, user);
```
2. 设置回调函数:
```cpp
// KCP的下层协议输出函数KCP需要发送数据时会调用它
// buf/len 表示缓存和长度
// user指针为 kcp对象创建时传入的值用于区别多个 KCP对象
int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
....
}
// 设置回调函数
kcp->output = udp_output;
```
3. 循环调用 update
```cpp
// 以一定频率调用 ikcp_update来更新 kcp状态并且传入当前时钟毫秒单位
// 如 10ms调用一次或用 ikcp_check确定下次调用 update的时间不必每次调用
ikcp_update(kcp, millisec);
```
4. 输入一个下层数据包:
```cpp
// 收到一个下层数据包比如UDP包时需要调用
ikcp_input(kcp, received_udp_packet, received_udp_size);
```
处理了下层协议的输出/输入后 KCP协议就可以正常工作了使用 ikcp_send 来向
远端发送数据。而另一端使用 ikcp_recv(kcp, ptr, size)来接收数据。
# 协议配置
协议默认模式是一个标准的 ARQ需要通过配置打开各项加速开关
1. 工作模式:
```cpp
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
```
- nodelay :是否启用 nodelay模式0不启用1启用。
- interval :协议内部工作的 interval单位毫秒比如 10ms或者 20ms
- resend 快速重传模式默认0关闭可以设置22次ACK跨越将会直接重传
- nc 是否关闭流控默认是0代表不关闭1代表关闭。
- 普通模式: ikcp_nodelay(kcp, 0, 40, 0, 0);
- 极速模式: ikcp_nodelay(kcp, 1, 10, 2, 1);
2. 最大窗口:
```cpp
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);
```
该调用将会设置协议的最大发送窗口和最大接收窗口大小默认为32. 这个可以理解为 TCP的 SND_BUF 和 RCV_BUF只不过单位不一样 SND/RCV_BUF 单位是字节,这个单位是包。
3. 最大传输单元:
纯算法协议并不负责探测 MTU默认 mtu是1400字节可以使用ikcp_setmtu来设置该值。该值将会影响数据包归并及分片时候的最大传输单元。
4. 最小RTO
不管是 TCP还是 KCP计算 RTO时都有最小 RTO的限制即便计算出来RTO为40ms由于默认的 RTO是100ms协议只有在100ms后才能检测到丢包快速模式下为30ms可以手动更改该值
```cpp
kcp->rx_minrto = 10;
```
# 文档索引
协议的使用和配置都是很简单的,大部分情况看完上面的内容基本可以使用了。如果你需要进一步进行精细的控制,比如改变 KCP的内存分配器或者你需要更有效的大规模调度 KCP链接比如 3500个以上或者如何更好的同 TCP结合那么可以继续延伸阅读
- [Wiki Home](https://github.com/skywind3000/kcp/wiki)
- [KCP 最佳实践](https://github.com/skywind3000/kcp/wiki/KCP-Best-Practice)
- [同现有TCP服务器集成](https://github.com/skywind3000/kcp/wiki/Cooperate-With-Tcp-Server)
- [传输数据加密](https://github.com/skywind3000/kcp/wiki/Network-Encryption)
- [应用层流量控制](https://github.com/skywind3000/kcp/wiki/Flow-Control-for-Users)
# 相关应用
- [应用层流量控制](https://github.com/skywind3000/kcp/wiki/Flow-Control-for-Users)
- [性能评测](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark)
- [dog-tunnel](https://github.com/vzex/dog-tunnel): GO开发的网络隧道使用 KCP极大的改进了传输速度并移植了一份 GO版本 KCP
- [lua-kcp](https://github.com/linxiaolong/lua-kcp)KCP的 Lua扩展用于 Lua服务器
# 欢迎捐赠
![欢迎使用支付宝对该项目进行捐赠](https://raw.githubusercontent.com/skywind3000/kcp/master/donation.png)
欢迎使用支付宝手扫描上面的二维码,对该项目进行捐赠。捐赠款项将用于改进 KCP性能以及
后续持续优化。
# 开源案例
- [kcptun](https://github.com/xtaci/kcptun): 基于 kcp-go做的高速远程端口转发(隧道) 配合ssh -D可以比 shadowsocks 更流畅的看在线视频。
- [dog-tunnel](https://github.com/vzex/dog-tunnel): GO开发的网络隧道使用 KCP极大的改进了传输速度并移植了一份 GO版本 KCP
- [v2ray](https://www.v2ray.com): 著名代理软件Shadowsocks 代替者1.17后集成了 kcp协议使用UDP传输无数据包特征。
- [HP-Socket](https://github.com/ldcsaa/HP-Socket): 高性能网络通信框架 HP-Socket。
- [frp](https://github.com/fatedier/frp): 高性能内网穿透的反向代理软件,可将将内网服务暴露映射到外网服务器。
- [asio-kcp](https://github.com/libinzhangyuan/asio_kcp): 使用 KCP的完整 UDP网络库完整实现了基于 UDP的链接状态管理会话控制KCP协议调度等
- [kcp-java](https://github.com/hkspirt/kcp-java): Java版本 KCP协议实现。
- [kcp-netty](https://github.com/szhnet/kcp-netty): kcp的Java语言实现基于netty。
- [java-kcp](https://github.com/l42111996/java-Kcp): JAVA版本KCP,基于netty实现(包含fec功能)
- [kcp.kt](https://github.com/jokelbaf/kcp.kt): 纯 Kotlin 多平台Kotlin Multiplatform实现的 KCP 协议,支持 JVM、Linux、Windows、macOS 和 iOS 等目标平台。
- [csharp-kcp](https://github.com/l42111996/csharp-kcp): csharp版本KCP,基于dotNetty实现(包含fec功能)
- [kcp-cpp](https://github.com/Unit-X/kcp-cpp): KCP 的多平台Windows、MacOS、LinuxC++ 实现作为应用程序中的简单库。包含适用于所有平台的套接字处理和辅助函数。
- [kcp-perl](https://github.com/Homqyy/kcp-perl): kcp的Perl实现其是面向对象的Perl-Like的。
- [kcp-go](https://github.com/xtaci/kcp-go): 高安全性的kcp的 GO语言实现包含 UDP会话管理的简单实现可以作为后续开发的基础库。
- [kcp-csharp](https://github.com/limpo1989/kcp-csharp): kcp的 csharp移植同时包含一份回话管理可以连接上面kcp-go的服务端。
- [kcp-csharp](https://github.com/KumoKyaku/KCP): 新版本 Kcp的 csharp移植。线程安全运行时无alloc对gc无压力。
- [KcpTransport](https://github.com/Cysharp/KcpTransport): kcp的csharp移植实现了 Syn Cookie 握手、连接管理、不可靠通信、KeepAlive未来还将支持加密。
- [Kcp-CSharp](https://github.com/Molth/Kcp-CSharp): kcp的csharp移植非托管包装器。
- [kcp2k](https://github.com/vis2k/kcp2k/): Line-by-line translation to C#, with optional Server/Client on top.
- [KcpSharpN](https://github.com/new1271/KcpSharpN): 将原始 C 语言源代码复刻到 Csharp 的移植,包含一个简易的协定包装器与原始的 KCP 协定呼叫
- [kcp-rs](https://github.com/en/kcp-rs): KCP的 rust移植
- [kcp-rust](https://github.com/Matrix-Zhang/kcp):新版本 KCP的 rust 移植
- [tokio-kcp](https://github.com/Matrix-Zhang/tokio_kcp)rust tokio 的 kcp 集成
- [kcp-rust-native](https://github.com/b23r0/kcp-rust-native)rust 的 kcp bindings
- [lua-kcp](https://github.com/linxiaolong/lua-kcp): KCP的 Lua扩展用于 Lua服务器
- [node-kcp](https://github.com/leenjewel/node-kcp): node-js 的 KCP 接口
- [nysocks](https://github.com/oyyd/nysocks): 基于libuv实现的[node-addon](https://nodejs.org/api/addons.html)提供nodejs版本的代理服务客户端接入支持SOCKS5和ss两种协议
- [shadowsocks-android](https://github.com/shadowsocks/shadowsocks-android): Shadowsocks for android 集成了 kcptun 使用 kcp协议加速 shadowsocks效果不错
- [kcpuv](https://github.com/elisaday/kcpuv): 使用 libuv开发的kcpuv库目前还在 Demo阶段
- [Lantern](https://getlantern.org/):更好的 VPNGithub 50000 星,使用 kcpgo 加速
- [rpcx](https://github.com/smallnest/rpcx) RPC 框架1000+ 星,使用 kcpgo 加速 RPC
- [xkcptun](https://github.com/liudf0716/xkcptun): c语言实现的kcptun主要用于[OpenWrt](https://github.com/openwrt/openwrt), [LEDE](https://github.com/lede-project/source)开发的路由器项目上
- [et-frame](https://github.com/egametang/ET): C#前后端框架(前端unity3d)统一用C#开发游戏实现了前后端kcp协议
- [yasio](https://github.com/yasio/yasio): 一个跨平台专注于任意客户端程序的异步socket库, 易于使用相同的API操作KCP/TCP/UDP, 性能测试结果: [benchmark-pump](https://github.com/yasio/yasio/blob/master/benchmark.md).
- [gouxp](https://github.com/shaoyuan1943/gouxp): 用Go实现基于回调方式的KCP开发包包含加解密和FEC支持简单易用。
- [skcp](https://github.com/xboss/skcp): 基于libev实现的库具备传输加密及基本的连接管理能力。
- [pykcp](https://github.com/enkiller/pykcp): Python 版本的 KCP 实现
- [php-ext-kcp](https://github.com/wpjscc/php-ext-kcp): php 的 KCP 扩展
- [asio-kcp(new)](https://github.com/sniper00/asio-kcp): c++的asio/kcp支持支持asio协程等现代c++异步模型
# 商业案例
- [原神](https://ys.mihoyo.com/):米哈游的《原神》使用 KCP 降低游戏消息的传输耗时,提升操作的体验。
- [SpatialOS](https://improbable.io/spatialOS): 大型多人分布式游戏服务端引擎BigWorld 的后继者,使用 KCP 加速数据传输。
- [西山居](https://www.xishanju.com/):使用 KCP 进行游戏数据加速。
- [CC](http://cc.163.com/):网易 CC 使用 kcp 加速视频推流,有效提高流畅性
- [BOBO](http://bobo.163.com/):网易 BOBO 使用 kcp 加速主播推流
- [UU](https://uu.163.com):网易 UU 加速器使用 KCP/KCPTUN 经行远程传输加速。
- [阿里云](https://cn.aliyun.com/):阿里云的视频传输加速服务 GRTN 使用 KCP 进行音视频数据传输优化,动态加速产品也使用 KCP。
- [云帆加速](http://www.yfcloud.com/):使用 KCP 加速文件传输和视频推流,优化了台湾主播推流的流畅度。
- [明日帝国](https://www.taptap.com/app/50664)Game K17 的 《明日帝国》 Google Play使用 KCP 加速游戏消息,让全球玩家流畅联网
- [仙灵大作战](https://www.taptap.com/app/27242)4399 的 MOBA游戏使用 KCP 优化游戏同步
相关阅读:[《原神》也在使用 KCP 加速游戏消息](https://skywind.me/blog/archives/2706)
KCP 成功的运行在多个用户规模上亿的项目上,为他们提供了更加灵敏和丝滑网络体验。
欢迎告知更多案例
# 协议比较
如果网络永远不卡,那 KCP/TCP 表现类似但是网络本身就是不可靠的丢包和抖动无法避免否则还要各种可靠协议干嘛。在内网这种几乎理想的环境里直接比较大家都差不多但是放到公网上放到3G/4G网络情况下或者使用内网丢包模拟差距就很明显了。公网在高峰期有平均接近10%的丢包wifi/3g/4g下更糟糕这些都会让传输变卡。
感谢 [asio-kcp](https://github.com/libinzhangyuan/asio_kcp) 的作者 [zhangyuan](https://github.com/libinzhangyuan) 对 KCP 与 enet, udt做过的一次横向评测结论如下
- ASIO-KCP **has good performace in wifi and phone network(3G, 4G)**.
- The kcp is the **first choice for realtime pvp game**.
- The lag is less than 1 second when network lag happen. **3 times better than enet** when lag happen.
- The enet is a good choice if your game allow 2 second lag.
- **UDT is a bad idea**. It always sink into badly situation of more than serval seconds lag. And the recovery is not expected.
- enet has the problem of lack of doc. And it has lots of functions that you may intrest.
- kcp's doc is chinese. Good thing is the function detail which is written in code is english. And you can use asio_kcp which is a good wrap.
- The kcp is a simple thing. You will write more code if you want more feature.
- UDT has a perfect doc. UDT may has more bug than others as I feeling.
具体见:[横向比较](https://github.com/libinzhangyuan/reliable_udp_bench_mark) 和 [评测数据](https://github.com/skywind3000/kcp/wiki/KCP-Benchmark),为犹豫选择的人提供了更多指引。
大型多人游戏服务端引擎 [SpatialOS](https://improbable.io/spatialOS) 在集成 KCP 协议后做了同 TCP/RakNet 的评测:
![](https://github.com/skywind3000/kcp/raw/master/images/spatialos-50.png)
对比了在服务端刷新率为 60 Hz 同时维护 50 个角色时的响应时间,详细对比报告见:
- [Kcp a new low latency secure network stack](https://improbable.io/blog/kcp-a-new-low-latency-secure-network-stack)
# 关于协议
近年来,网络游戏和各类社交网络都在成几何倍数的增长,不管网络游戏还是各类互动社交网络,交互性和复杂度都在迅速提高,都需要在极短的时间内将数据同时投递给大量用户,因此传输技术自然变为未来制约发展的一个重要因素,而开源界里各种著名的传输协议,如 raknet/enet 之类,一发布都是整套协议栈一起发布,这种形式是不利于多样化的,我的项目只能选择用或者不用你,很难选择 “部分用你”,然而你一套协议栈设计的再好,是非常难以满足不同角度的各种需求的。
因此 KCP 的方式是把协议栈 “拆开”,让大家可以根据项目需求进行灵活的调整和组装,你可以下面加一层 reed solomon 的纠删码做 FEC上面加一层类 RC4/Salsa20 做流加密,握手处再设计一套非对称密钥交换,底层 UDP 传输层再做一套动态路由系统,同时探测多条路径,选最好路径进行传输。这些不同的 “协议单元” 可以像搭建积木一般根据需要自由组合,保证 “简单性” 和 “可拆分性”,这样才能灵活适配多变的业务需求,哪个模块不好,换了就是。
未来传输方面的解决方案必然是根据使用场景深度定制的,因此给大家一个可以自由组合的 “协议单元” ,方便大家集成在自己的协议栈中。
For more information, please see the [Success Stories](https://github.com/skywind3000/kcp/wiki/Success-Stories).
# 关于作者
作者:林伟 (skywind3000)
欢迎关注我的:[个人博客](https://skywind.me/blog) 和 [推特](https://x.com/skywind3000)。
我在多年的开发经历中一直都喜欢研究解决程序中的一些瓶颈问题早年喜欢游戏开发照着《VGA编程》来做游戏图形读 Michael Abrash 的《图形程序开发人员指南》做软渲染器,爱好摆弄一些能够榨干 CPU 能够运行更快的代码,参加工作后,兴趣转移到服务端和网络相关的技术。
2007 年时做了几个传统游戏后开始研究快速动作游戏的同步问题,期间写过不少文章,算是国内比较早研究同步问题的人,然而发现不管怎么解决同步都需要在网络传输方面有所突破,后来离开游戏转行互联网后也发现不少领域有这方面的需求,于是开始花时间在网络传输这个领域上,尝试基于 UDP 实现一些保守的可靠协议,仿照 BSD Lite 4.4 的代码实现一些类 TCP 协议,觉得比较有意思,又接着实现一些 P2P 和动态路由网相关的玩具。KCP 协议诞生于 2011 年,基本算是自己传输方面做的几个玩具中的一个。
Kcptun 的作者 xtaci 是我的大学同学,我俩都是学通信的,经常在一起研究如何进行传输优化。
# 欢迎捐赠
![欢迎使用支付宝对该项目进行捐赠](images/donation.png)
欢迎使用支付宝手扫描上面的二维码,对该项目进行捐赠。捐赠款项将用于持续优化 KCP协议以及完善文档。
感谢:明明、星仔、进、帆、颁钊、斌铨、晓丹、余争、虎、晟敢、徐玮、王川、赵刚强、胡知锋、万新朝、何新超、刘旸、侯宪辉、吴佩仪、华斌、如涛、胡坚。。。(早先的名单实在不好意思没记录下来)等同学的捐助与支持。
欢迎关注
KCP交流群364933586QQ群号KCP集成调优网络传输以及相关技术讨论
Gitter 群https://gitter.im/skywind3000/KCP
blog: http://www.skywind.me
## Contributors
This project exists thanks to all the people who contribute.
<a href="https://github.com/skywind3000/kcp/graphs/contributors"><img src="https://opencollective.com/kcp/contributors.svg?width=890&button=false" /></a>

BIN
benchmark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

410
ikcp.c
View File

@@ -15,8 +15,9 @@
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#define IKCP_FASTACK_CONSERVE
//=====================================================================
// KCP BASIC
@@ -32,16 +33,17 @@ const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell)
const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK
const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS
const IUINT32 IKCP_WND_SND = 32;
const IUINT32 IKCP_WND_RCV = 32;
const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size
const IUINT32 IKCP_MTU_DEF = 1400;
const IUINT32 IKCP_ACK_FAST = 3;
const IUINT32 IKCP_INTERVAL = 100;
const IUINT32 IKCP_OVERHEAD = 24;
const IUINT32 IKCP_DEADLINK = 10;
const IUINT32 IKCP_DEADLINK = 20;
const IUINT32 IKCP_THRESH_INIT = 2;
const IUINT32 IKCP_THRESH_MIN = 2;
const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size
const IUINT32 IKCP_PROBE_INIT = 5000; // 7 secs to probe window size
const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window
const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack
//---------------------------------------------------------------------
@@ -65,11 +67,11 @@ static inline const char *ikcp_decode8u(const char *p, unsigned char *c)
/* encode 16 bits unsigned int (lsb) */
static inline char *ikcp_encode16u(char *p, unsigned short w)
{
#if IWORDS_BIG_ENDIAN
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*(unsigned char*)(p + 0) = (w & 255);
*(unsigned char*)(p + 1) = (w >> 8);
#else
*(unsigned short*)(p) = w;
memcpy(p, &w, 2);
#endif
p += 2;
return p;
@@ -78,11 +80,11 @@ static inline char *ikcp_encode16u(char *p, unsigned short w)
/* decode 16 bits unsigned int (lsb) */
static inline const char *ikcp_decode16u(const char *p, unsigned short *w)
{
#if IWORDS_BIG_ENDIAN
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*w = *(const unsigned char*)(p + 1);
*w = *(const unsigned char*)(p + 0) + (*w << 8);
#else
*w = *(const unsigned short*)p;
memcpy(w, p, 2);
#endif
p += 2;
return p;
@@ -91,13 +93,13 @@ static inline const char *ikcp_decode16u(const char *p, unsigned short *w)
/* encode 32 bits unsigned int (lsb) */
static inline char *ikcp_encode32u(char *p, IUINT32 l)
{
#if IWORDS_BIG_ENDIAN
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff);
*(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff);
*(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff);
*(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff);
#else
*(IUINT32*)p = l;
memcpy(p, &l, 4);
#endif
p += 4;
return p;
@@ -106,13 +108,13 @@ static inline char *ikcp_encode32u(char *p, IUINT32 l)
/* decode 32 bits unsigned int (lsb) */
static inline const char *ikcp_decode32u(const char *p, IUINT32 *l)
{
#if IWORDS_BIG_ENDIAN
#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN
*l = *(const unsigned char*)(p + 3);
*l = *(const unsigned char*)(p + 2) + (*l << 8);
*l = *(const unsigned char*)(p + 1) + (*l << 8);
*l = *(const unsigned char*)(p + 0) + (*l << 8);
#else
*l = *(const IUINT32*)p;
memcpy(l, p, 4);
#endif
p += 4;
return p;
@@ -250,6 +252,7 @@ ikcpcb* ikcp_create(IUINT32 conv, void *user)
kcp->probe = 0;
kcp->mtu = IKCP_MTU_DEF;
kcp->mss = kcp->mtu - IKCP_OVERHEAD;
kcp->stream = 0;
kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3);
if (kcp->buffer == NULL) {
@@ -269,6 +272,7 @@ ikcpcb* ikcp_create(IUINT32 conv, void *user)
kcp->acklist = NULL;
kcp->ackblock = 0;
kcp->ackcount = 0;
kcp->ackedlen = 0;
kcp->rx_srtt = 0;
kcp->rx_rttval = 0;
kcp->rx_rto = IKCP_RTO_DEF;
@@ -281,10 +285,13 @@ ikcpcb* ikcp_create(IUINT32 conv, void *user)
kcp->logmask = 0;
kcp->ssthresh = IKCP_THRESH_INIT;
kcp->fastresend = 0;
kcp->fastlimit = IKCP_FASTACK_LIMIT;
kcp->nocwnd = 0;
kcp->xmit = 0;
kcp->dead_link = IKCP_DEADLINK;
kcp->dead_link = IKCP_DEADLINK;
kcp->output = NULL;
kcp->ccops = NULL;
kcp->congest = NULL;
kcp->writelog = NULL;
return kcp;
@@ -292,13 +299,16 @@ ikcpcb* ikcp_create(IUINT32 conv, void *user)
//---------------------------------------------------------------------
// release a new kcpcb
// release a kcpcb
//---------------------------------------------------------------------
void ikcp_release(ikcpcb *kcp)
{
IKCPSEG *seg;
assert(kcp);
if (kcp) {
IKCPSEG *seg;
if (kcp->ccops && kcp->ccops->release) {
kcp->ccops->release(kcp);
}
while (!iqueue_is_empty(&kcp->snd_buf)) {
seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node);
iqueue_del(&seg->node);
@@ -338,9 +348,18 @@ void ikcp_release(ikcpcb *kcp)
}
//---------------------------------------------------------------------
// set output callback, which will be invoked by kcp
//---------------------------------------------------------------------
void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len,
ikcpcb *kcp, void *user))
{
kcp->output = output;
}
//---------------------------------------------------------------------
// user/upper level recv: returns size, returns below zero for EAGAIN
// upper-level recv: returns size, or a negative value for EAGAIN
//---------------------------------------------------------------------
int ikcp_recv(ikcpcb *kcp, char *buffer, int len)
{
@@ -382,7 +401,7 @@ int ikcp_recv(ikcpcb *kcp, char *buffer, int len)
fragment = seg->frg;
if (ikcp_canlog(kcp, IKCP_LOG_RECV)) {
ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", seg->sn);
ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn);
}
if (ispeek == 0) {
@@ -399,7 +418,7 @@ int ikcp_recv(ikcpcb *kcp, char *buffer, int len)
// move available data from rcv_buf -> rcv_queue
while (! iqueue_is_empty(&kcp->rcv_buf)) {
IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node);
if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) {
iqueue_del(&seg->node);
kcp->nrcv_buf--;
@@ -451,20 +470,56 @@ int ikcp_peeksize(const ikcpcb *kcp)
//---------------------------------------------------------------------
// user/upper level send, returns below zero for error
// upper-level send: returns size, or a negative value on error
//---------------------------------------------------------------------
int ikcp_send(ikcpcb *kcp, const char *buffer, int len)
{
IKCPSEG *seg;
int count, i;
int sent = 0;
assert(kcp->mss > 0);
if (len < 0) return -1;
// append to previous segment in streaming mode (if possible)
if (kcp->stream != 0) {
if (!iqueue_is_empty(&kcp->snd_queue)) {
IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node);
if (old->len < kcp->mss) {
int capacity = kcp->mss - old->len;
int extend = (len < capacity)? len : capacity;
seg = ikcp_segment_new(kcp, old->len + extend);
assert(seg);
if (seg == NULL) {
return -2;
}
iqueue_add_tail(&seg->node, &kcp->snd_queue);
memcpy(seg->data, old->data, old->len);
if (buffer) {
memcpy(seg->data + old->len, buffer, extend);
buffer += extend;
}
seg->len = old->len + extend;
seg->frg = 0;
len -= extend;
iqueue_del_init(&old->node);
ikcp_segment_delete(kcp, old);
sent = extend;
}
}
if (len <= 0) {
return sent;
}
}
if (len <= (int)kcp->mss) count = 1;
else count = (len + kcp->mss - 1) / kcp->mss;
if (count > 255) return -2;
if (count >= (int)IKCP_WND_RCV) {
if (kcp->stream != 0 && sent > 0)
return sent;
return -2;
}
if (count == 0) count = 1;
@@ -480,7 +535,7 @@ int ikcp_send(ikcpcb *kcp, const char *buffer, int len)
memcpy(seg->data, buffer, size);
}
seg->len = size;
seg->frg = count - i - 1;
seg->frg = (kcp->stream == 0)? (count - i - 1) : 0;
iqueue_init(&seg->node);
iqueue_add_tail(&seg->node, &kcp->snd_queue);
kcp->nsnd_que++;
@@ -488,9 +543,10 @@ int ikcp_send(ikcpcb *kcp, const char *buffer, int len)
buffer += size;
}
len -= size;
sent += size;
}
return 0;
return sent;
}
@@ -510,8 +566,11 @@ static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt)
kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8;
if (kcp->rx_srtt < 1) kcp->rx_srtt = 1;
}
rto = kcp->rx_srtt + _imax_(1, 4 * kcp->rx_rttval);
rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval);
kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX);
if (kcp->ccops && kcp->ccops->on_rtt) {
kcp->ccops->on_rtt(kcp, rtt);
}
}
static void ikcp_shrink_buf(ikcpcb *kcp)
@@ -528,6 +587,7 @@ static void ikcp_shrink_buf(ikcpcb *kcp)
static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn)
{
struct IQUEUEHEAD *p, *next;
IINT32 pkt_rtt;
if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
return;
@@ -536,25 +596,38 @@ static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn)
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (sn == seg->sn) {
kcp->ackedlen += seg->len;
if (kcp->ccops && kcp->ccops->on_pkt_acked) {
pkt_rtt = -1;
if (_itimediff(kcp->current, seg->ts) >= 0) {
pkt_rtt = _itimediff(kcp->current, seg->ts);
}
kcp->ccops->on_pkt_acked(kcp, seg->sn, seg->ts,
seg->len, pkt_rtt, seg->xmit);
}
iqueue_del(p);
ikcp_segment_delete(kcp, seg);
kcp->nsnd_buf--;
break;
}
else {
seg->fastack++;
if (_itimediff(sn, seg->sn) < 0) {
break;
}
}
}
static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una)
{
#if 1
struct IQUEUEHEAD *p, *next;
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (_itimediff(una, seg->sn) > 0) {
kcp->ackedlen += seg->len;
if (kcp->ccops && kcp->ccops->on_pkt_acked) {
kcp->ccops->on_pkt_acked(kcp, seg->sn, seg->ts,
seg->len, -1, seg->xmit);
}
iqueue_del(p);
ikcp_segment_delete(kcp, seg);
kcp->nsnd_buf--;
@@ -562,7 +635,30 @@ static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una)
break;
}
}
#endif
}
static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
{
struct IQUEUEHEAD *p, *next;
if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0)
return;
for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) {
IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node);
next = p->next;
if (_itimediff(sn, seg->sn) < 0) {
break;
}
else if (sn != seg->sn) {
#ifndef IKCP_FASTACK_CONSERVE
seg->fastack++;
#else
if (_itimediff(ts, seg->ts) >= 0)
seg->fastack++;
#endif
}
}
}
@@ -571,12 +667,12 @@ static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una)
//---------------------------------------------------------------------
static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
{
size_t newsize = kcp->ackcount + 1;
IUINT32 newsize = kcp->ackcount + 1;
IUINT32 *ptr;
if (newsize > kcp->ackblock) {
IUINT32 *acklist;
size_t newblock;
IUINT32 newblock;
for (newblock = 8; newblock < newsize; newblock <<= 1);
acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2);
@@ -587,7 +683,7 @@ static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts)
}
if (kcp->acklist != NULL) {
size_t x;
IUINT32 x;
for (x = 0; x < kcp->ackcount; x++) {
acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0];
acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1];
@@ -683,13 +779,19 @@ void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg)
//---------------------------------------------------------------------
int ikcp_input(ikcpcb *kcp, const char *data, long size)
{
IUINT32 una = kcp->snd_una;
IUINT32 prev_una = kcp->snd_una;
IUINT32 prev_nsnd_buf = kcp->nsnd_buf;
IUINT32 acked_segs, prior_in_flight;
IUINT32 maxack = 0, latest_ts = 0;
int flag = 0;
kcp->ackedlen = 0;
if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) {
ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", size);
ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size);
}
if (data == NULL || size < 24) return 0;
if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1;
while (1) {
IUINT32 ts, sn, len, una, conv;
@@ -712,7 +814,7 @@ int ikcp_input(ikcpcb *kcp, const char *data, long size)
size -= IKCP_OVERHEAD;
if ((long)size < (long)len) return -2;
if ((long)size < (long)len || (int)len < 0) return -2;
if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK &&
cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS)
@@ -728,9 +830,26 @@ int ikcp_input(ikcpcb *kcp, const char *data, long size)
}
ikcp_parse_ack(kcp, sn);
ikcp_shrink_buf(kcp);
if (flag == 0) {
flag = 1;
maxack = sn;
latest_ts = ts;
} else {
if (_itimediff(sn, maxack) > 0) {
#ifndef IKCP_FASTACK_CONSERVE
maxack = sn;
latest_ts = ts;
#else
if (_itimediff(ts, latest_ts) > 0) {
maxack = sn;
latest_ts = ts;
}
#endif
}
}
if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) {
ikcp_log(kcp, IKCP_LOG_IN_DATA,
"input ack: sn=%lu rtt=%ld rto=%ld", sn,
ikcp_log(kcp, IKCP_LOG_IN_ACK,
"input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn,
(long)_itimediff(kcp->current, ts),
(long)kcp->rx_rto);
}
@@ -738,7 +857,7 @@ int ikcp_input(ikcpcb *kcp, const char *data, long size)
else if (cmd == IKCP_CMD_PUSH) {
if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) {
ikcp_log(kcp, IKCP_LOG_IN_DATA,
"input psh: sn=%lu ts=%lu", sn, ts);
"input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts);
}
if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) {
ikcp_ack_push(kcp, sn, ts);
@@ -773,7 +892,7 @@ int ikcp_input(ikcpcb *kcp, const char *data, long size)
// do nothing
if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) {
ikcp_log(kcp, IKCP_LOG_IN_WINS,
"input wins: %lu", (IUINT32)(wnd));
"input wins: %lu", (unsigned long)(wnd));
}
}
else {
@@ -784,22 +903,38 @@ int ikcp_input(ikcpcb *kcp, const char *data, long size)
size -= len;
}
if (_itimediff(kcp->snd_una, una) > 0) {
if (kcp->cwnd < kcp->rmt_wnd) {
IUINT32 mss = kcp->mss;
if (kcp->cwnd < kcp->ssthresh) {
kcp->cwnd++;
kcp->incr += mss;
} else {
if (kcp->incr < mss) kcp->incr = mss;
kcp->incr += (mss * mss) / kcp->incr + (mss / 16);
if ((kcp->cwnd + 1) * mss <= kcp->incr) {
if (flag != 0) {
ikcp_parse_fastack(kcp, maxack, latest_ts);
}
if (_itimediff(kcp->snd_una, prev_una) > 0) {
acked_segs = kcp->snd_una - prev_una;
prior_in_flight = prev_nsnd_buf;
if (kcp->ccops && kcp->ccops->on_ack) {
kcp->ccops->on_ack(kcp, acked_segs, kcp->ackedlen,
prior_in_flight);
}
else {
if (kcp->cwnd < kcp->rmt_wnd) {
IUINT32 mss = kcp->mss;
if (kcp->cwnd < kcp->ssthresh) {
kcp->cwnd++;
kcp->incr += mss;
} else {
if (kcp->incr < mss) kcp->incr = mss;
kcp->incr += (mss * mss) / kcp->incr + (mss / 16);
if ((kcp->cwnd + 1) * mss <= kcp->incr) {
#if 1
kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1);
#else
kcp->cwnd++;
#endif
}
}
if (kcp->cwnd > kcp->rmt_wnd) {
kcp->cwnd = kcp->rmt_wnd;
kcp->incr = kcp->rmt_wnd * mss;
}
}
if (kcp->cwnd > kcp->rmt_wnd) {
kcp->cwnd = kcp->rmt_wnd;
kcp->incr = kcp->rmt_wnd * mss;
}
}
}
@@ -844,14 +979,27 @@ void ikcp_flush(ikcpcb *kcp)
int count, size, i;
IUINT32 resent, cwnd;
IUINT32 rtomin;
IUINT32 prior_cwnd;
IUINT32 eff_cwnd, cur_inflight;
IINT32 pacing_budget = -1;
struct IQUEUEHEAD *p;
int change = 0;
int lost = 0;
IKCPSEG seg;
// 'ikcp_update' haven't been called.
// 'ikcp_update' hasn't been called yet.
if (kcp->updated == 0) return;
if (kcp->ccops && kcp->ccops->on_tick) {
kcp->ccops->on_tick(kcp);
}
if (kcp->ccops && kcp->ccops->pacing_rate) {
pacing_budget = (IINT32)kcp->ccops->pacing_rate(kcp);
}
prior_cwnd = kcp->cwnd;
seg.conv = kcp->conv;
seg.cmd = IKCP_CMD_ACK;
seg.frg = 0;
@@ -865,7 +1013,7 @@ void ikcp_flush(ikcpcb *kcp)
count = kcp->ackcount;
for (i = 0; i < count; i++) {
size = (int)(ptr - buffer);
if (size + IKCP_OVERHEAD > (int)kcp->mtu) {
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
@@ -901,7 +1049,7 @@ void ikcp_flush(ikcpcb *kcp)
if (kcp->probe & IKCP_ASK_SEND) {
seg.cmd = IKCP_CMD_WASK;
size = (int)(ptr - buffer);
if (size + IKCP_OVERHEAD > (int)kcp->mtu) {
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
@@ -912,7 +1060,7 @@ void ikcp_flush(ikcpcb *kcp)
if (kcp->probe & IKCP_ASK_TELL) {
seg.cmd = IKCP_CMD_WINS;
size = (int)(ptr - buffer);
if (size + IKCP_OVERHEAD > (int)kcp->mtu) {
if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) {
ikcp_output(kcp, buffer, size);
ptr = buffer;
}
@@ -923,7 +1071,7 @@ void ikcp_flush(ikcpcb *kcp)
// calculate window size
cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd);
if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd);
if (kcp->ccops != NULL || kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd);
// move data from snd_queue to snd_buf
while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) {
@@ -949,6 +1097,18 @@ void ikcp_flush(ikcpcb *kcp)
newseg->xmit = 0;
}
// check on_app_limited
if (kcp->ccops && kcp->ccops->on_app_limited) {
if (iqueue_is_empty(&kcp->snd_queue)) {
eff_cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd);
eff_cwnd = _imin_(kcp->cwnd, eff_cwnd);
cur_inflight = kcp->nsnd_buf;
if (cur_inflight < eff_cwnd) {
kcp->ccops->on_app_limited(kcp, cur_inflight);
}
}
}
// calculate resent
resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff;
rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0;
@@ -968,27 +1128,41 @@ void ikcp_flush(ikcpcb *kcp)
segment->xmit++;
kcp->xmit++;
if (kcp->nodelay == 0) {
segment->rto += kcp->rx_rto;
segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto);
} else {
segment->rto += kcp->rx_rto / 2;
IINT32 step = (kcp->nodelay < 2)?
((IINT32)(segment->rto)) : kcp->rx_rto;
segment->rto += step / 2;
}
segment->resendts = current + segment->rto;
lost = 1;
}
else if (segment->fastack >= resent) {
needsend = 1;
segment->xmit++;
segment->fastack = 0;
segment->resendts = current + segment->rto;
change++;
if ((int)segment->xmit <= kcp->fastlimit ||
kcp->fastlimit <= 0) {
needsend = 1;
segment->xmit++;
segment->fastack = 0;
segment->resendts = current + segment->rto;
change++;
}
}
if (needsend) {
int size, need;
int need;
segment->ts = current;
segment->wnd = seg.wnd;
segment->una = kcp->rcv_nxt;
if (pacing_budget >= 0 && pacing_budget < (IINT32)segment->len) {
break;
}
if (kcp->ccops && kcp->ccops->on_pkt_sent) {
kcp->ccops->on_pkt_sent(kcp, segment->sn, current,
segment->len, kcp->nsnd_buf, segment->xmit);
}
size = (int)(ptr - buffer);
need = IKCP_OVERHEAD + segment->len;
@@ -1004,13 +1178,17 @@ void ikcp_flush(ikcpcb *kcp)
ptr += segment->len;
}
if (pacing_budget >= 0) {
pacing_budget -= (IINT32)segment->len;
}
if (segment->xmit >= kcp->dead_link) {
kcp->state = -1;
kcp->state = (IUINT32)-1;
}
}
}
// flash remain segments
// flash remaining segments
size = (int)(ptr - buffer);
if (size > 0) {
ikcp_output(kcp, buffer, size);
@@ -1018,20 +1196,31 @@ void ikcp_flush(ikcpcb *kcp)
// update ssthresh
if (change) {
IUINT32 inflight = kcp->snd_nxt - kcp->snd_una;
kcp->ssthresh = inflight / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = kcp->ssthresh + resent;
kcp->incr = kcp->cwnd * kcp->mss;
if (kcp->ccops && kcp->ccops->on_fast_retransmit) {
kcp->ccops->on_fast_retransmit(kcp, (IUINT32)change,
kcp->nsnd_buf, prior_cwnd);
}
else {
IUINT32 inflight = kcp->snd_nxt - kcp->snd_una;
kcp->ssthresh = inflight / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = kcp->ssthresh + resent;
kcp->incr = kcp->cwnd * kcp->mss;
}
}
if (lost) {
kcp->ssthresh = cwnd / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = 1;
kcp->incr = kcp->mss;
if (kcp->ccops && kcp->ccops->on_timeout) {
kcp->ccops->on_timeout(kcp, prior_cwnd);
}
else {
kcp->ssthresh = prior_cwnd / 2;
if (kcp->ssthresh < IKCP_THRESH_MIN)
kcp->ssthresh = IKCP_THRESH_MIN;
kcp->cwnd = 1;
kcp->incr = kcp->mss;
}
}
if (kcp->cwnd < 1) {
@@ -1042,9 +1231,9 @@ void ikcp_flush(ikcpcb *kcp)
//---------------------------------------------------------------------
// update state (call it repeatedly, every 10ms-100ms), or you can ask
// ikcp_check when to call it again (without ikcp_input/_send calling).
// 'current' - current timestamp in millisec.
// update state (call it repeatedly, every 10ms-100ms), or you can ask
// ikcp_check when to call it again (if no ikcp_input/_send calls occur).
// 'current' - current timestamp in milliseconds.
//---------------------------------------------------------------------
void ikcp_update(ikcpcb *kcp, IUINT32 current)
{
@@ -1075,13 +1264,13 @@ void ikcp_update(ikcpcb *kcp, IUINT32 current)
//---------------------------------------------------------------------
// Determine when should you invoke ikcp_update:
// returns when you should invoke ikcp_update in millisec, if there
// is no ikcp_input/_send calling. you can call ikcp_update in that
// time, instead of call update repeatly.
// Important to reduce unnacessary ikcp_update invoking. use it to
// schedule ikcp_update (eg. implementing an epoll-like mechanism,
// or optimize ikcp_update when handling massive kcp connections)
// Determines when you should invoke ikcp_update next:
// returns the timestamp (in milliseconds) at which you should call
// ikcp_update, assuming no ikcp_input/_send calls occur in between.
// You can call ikcp_update at that time instead of calling it repeatedly.
// Important for reducing unnecessary ikcp_update invocations. Use it to
// schedule ikcp_update (e.g., implementing an epoll-like mechanism,
// or optimizing ikcp_update when handling massive kcp connections).
//---------------------------------------------------------------------
IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current)
{
@@ -1178,8 +1367,8 @@ int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd)
if (sndwnd > 0) {
kcp->snd_wnd = sndwnd;
}
if (rcvwnd > 0) {
kcp->rcv_wnd = rcvwnd;
if (rcvwnd > 0) { // must >= max fragment size
kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV);
}
}
return 0;
@@ -1191,3 +1380,44 @@ int ikcp_waitsnd(const ikcpcb *kcp)
}
// read conv
IUINT32 ikcp_getconv(const void *ptr)
{
IUINT32 conv;
ikcp_decode32u((const char*)ptr, &conv);
return conv;
}
//---------------------------------------------------------------------
// install congestion control
//---------------------------------------------------------------------
int ikcp_setcc(ikcpcb *kcp, const struct IKCPOPS *ops)
{
assert(kcp);
if (kcp->ccops && kcp->ccops->release) {
kcp->ccops->release(kcp);
}
kcp->congest = NULL;
kcp->ccops = ops;
if (ops) {
if (ops->init) {
if (ops->init(kcp) < 0) {
kcp->ccops = NULL;
kcp->congest = NULL;
if (kcp->cwnd < 1) kcp->cwnd = 1;
kcp->incr = kcp->cwnd * kcp->mss;
return -1;
}
}
}
else {
if (kcp->cwnd < 1) kcp->cwnd = 1;
kcp->incr = kcp->cwnd * kcp->mss;
if (kcp->incr < kcp->mss) kcp->incr = kcp->mss;
}
return 0;
}

105
ikcp.h
View File

@@ -9,8 +9,8 @@
// + Lightweight, distributed as a single source file.
//
//=====================================================================
#ifndef __IKCP_H__
#define __IKCP_H__
#ifndef _IKCP_H_
#define _IKCP_H_
#include <stddef.h>
#include <stdlib.h>
@@ -123,7 +123,7 @@ typedef unsigned long long IUINT64;
#endif
#endif
#ifndef inline
#if (!defined(__cplusplus)) && (!defined(inline))
#define inline INLINE
#endif
@@ -225,7 +225,7 @@ typedef struct IQUEUEHEAD iqueue_head;
//---------------------------------------------------------------------
// WORD ORDER
// BYTE ORDER & ALIGNMENT
//---------------------------------------------------------------------
#ifndef IWORDS_BIG_ENDIAN
#ifdef _BIG_ENDIAN_
@@ -236,7 +236,7 @@ typedef struct IQUEUEHEAD iqueue_head;
#ifndef IWORDS_BIG_ENDIAN
#if defined(__hppa__) || \
defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
(defined(__MIPS__) && defined(__MISPEB__)) || \
(defined(__MIPS__) && defined(__MIPSEB__)) || \
defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
defined(__sparc__) || defined(__powerpc__) || \
defined(__mc68000__) || defined(__s390x__) || defined(__s390__)
@@ -248,6 +248,24 @@ typedef struct IQUEUEHEAD iqueue_head;
#endif
#endif
#ifndef IWORDS_MUST_ALIGN
#if defined(__i386__) || defined(__i386) || defined(_i386_)
#define IWORDS_MUST_ALIGN 0
#elif defined(_M_IX86) || defined(_X86_) || defined(__x86_64__)
#define IWORDS_MUST_ALIGN 0
#elif defined(__amd64) || defined(__amd64__)
#define IWORDS_MUST_ALIGN 0
#else
#define IWORDS_MUST_ALIGN 1
#endif
#endif
//=====================================================================
// Predefine struct
//=====================================================================
struct IKCPCB;
typedef struct IKCPCB ikcpcb;
//=====================================================================
@@ -272,6 +290,31 @@ struct IKCPSEG
};
//---------------------------------------------------------------------
// IKCPOPS - pluggable congestion control operations
//---------------------------------------------------------------------
struct IKCPOPS
{
const char *name;
int (*init)(ikcpcb *kcp);
void (*release)(ikcpcb *kcp);
void (*on_ack)(ikcpcb *kcp, IUINT32 acked_segs, IUINT32 acked_bytes,
IUINT32 prior_in_flight);
void (*on_fast_retransmit)(ikcpcb *kcp, IUINT32 fast_retrans,
IUINT32 inflight, IUINT32 prior_cwnd);
void (*on_timeout)(ikcpcb *kcp, IUINT32 prior_cwnd);
void (*on_tick)(ikcpcb *kcp);
void (*on_app_limited)(ikcpcb *kcp, IUINT32 inflight);
void (*on_rtt)(ikcpcb *kcp, IINT32 rtt);
void (*on_pkt_sent)(ikcpcb *kcp, IUINT32 sn, IUINT32 ts,
IUINT32 len, IUINT32 inflight, IUINT32 xmit);
void (*on_pkt_acked)(ikcpcb *kcp, IUINT32 sn, IUINT32 ts,
IUINT32 len, IINT32 rtt, IUINT32 xmit);
IUINT32 (*get_info)(ikcpcb *kcp, void *buf, IUINT32 bufsize);
IUINT32 (*pacing_rate)(ikcpcb *kcp);
};
//---------------------------------------------------------------------
// IKCPCB
//---------------------------------------------------------------------
@@ -295,18 +338,20 @@ struct IKCPCB
IUINT32 *acklist;
IUINT32 ackcount;
IUINT32 ackblock;
IUINT32 ackedlen;
void *user;
char *buffer;
int fastresend;
int nocwnd;
int fastlimit;
int nocwnd, stream;
const struct IKCPOPS *ccops;
void *congest;
int logmask;
int (*output)(const char *buf, int len, struct IKCPCB *kcp, void *user);
void (*writelog)(const char *log, struct IKCPCB *kcp, void *user);
};
typedef struct IKCPCB ikcpcb;
#define IKCP_LOG_OUTPUT 1
#define IKCP_LOG_INPUT 2
#define IKCP_LOG_SEND 4
@@ -328,14 +373,18 @@ extern "C" {
// interface
//---------------------------------------------------------------------
// create a new kcp control object, 'conv' must equal in two endpoint
// from the same connection. 'user' will be passed to the output callback
// output callback can be setup like this: 'kcp->output = my_udp_output'
// create a new kcp control object, 'conv' must be equal in both endpoints
// of the same connection. 'user' will be passed to the output callback.
// output callback can be set up like this: 'kcp->output = my_udp_output'
ikcpcb* ikcp_create(IUINT32 conv, void *user);
// release kcp control object
void ikcp_release(ikcpcb *kcp);
// set output callback, which will be invoked by kcp
void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len,
ikcpcb *kcp, void *user));
// user/upper level recv: returns size, returns below zero for EAGAIN
int ikcp_recv(ikcpcb *kcp, char *buffer, int len);
@@ -347,16 +396,16 @@ int ikcp_send(ikcpcb *kcp, const char *buffer, int len);
// 'current' - current timestamp in millisec.
void ikcp_update(ikcpcb *kcp, IUINT32 current);
// Determine when should you invoke ikcp_update:
// returns when you should invoke ikcp_update in millisec, if there
// is no ikcp_input/_send calling. you can call ikcp_update in that
// time, instead of call update repeatly.
// Important to reduce unnacessary ikcp_update invoking. use it to
// schedule ikcp_update (eg. implementing an epoll-like mechanism,
// or optimize ikcp_update when handling massive kcp connections)
// Determines when you should invoke ikcp_update next:
// returns the timestamp (in milliseconds) at which you should call
// ikcp_update, assuming no ikcp_input/_send calls occur in between.
// You can call ikcp_update at that time instead of calling it repeatedly.
// Important for reducing unnecessary ikcp_update invocations. Use it to
// schedule ikcp_update (e.g., implementing an epoll-like mechanism,
// or optimizing ikcp_update when handling massive kcp connections).
IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current);
// when you received a low level packet (eg. UDP packet), call it
// when you receive a low-level packet (e.g., UDP packet), call this
int ikcp_input(ikcpcb *kcp, const char *data, long size);
// flush pending data
@@ -371,24 +420,28 @@ int ikcp_setmtu(ikcpcb *kcp, int mtu);
// set maximum window size: sndwnd=32, rcvwnd=32 by default
int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);
// get how many packet is waiting to be sent
// get how many packets are waiting to be sent
int ikcp_waitsnd(const ikcpcb *kcp);
// fastest: ikcp_nodelay(kcp, 1, 20, 2, 1)
// nodelay: 0:disable(default), 1:enable
// interval: internal update timer interval in millisec, default is 100ms
// resend: 0:disable fast resend(default), 1:enable fast resend
// nc: 0:normal congestion control(default), 1:disable congestion control
// nodelay: 0:disable (default), 1:enable
// interval: internal update timer interval in ms, default is 100ms
// resend: 0:disable fast resend (default), 1:enable fast resend
// nc: 0:normal congestion control (default), 1:disable congestion control
int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc);
int ikcp_rcvbuf_count(const ikcpcb *kcp);
int ikcp_sndbuf_count(const ikcpcb *kcp);
// install congestion control algorithm, NULL restores builtin
int ikcp_setcc(ikcpcb *kcp, const struct IKCPOPS *ops);
// write log with kcp->writelog
void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...);
// setup allocator
void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*));
// read conv
IUINT32 ikcp_getconv(const void *ptr);
#ifdef __cplusplus
}

View File

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
images/spatialos-25.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

BIN
images/spatialos-50.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

1
kcp.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="88" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><mask id="a"><rect width="88" height="20" rx="3" fill="#fff"/></mask><g mask="url(#a)"><path fill="#555" d="M0 0h31v20H0z"/><path fill="#007ec6" d="M31 0h57v20H31z"/><path fill="url(#b)" d="M0 0h88v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"><text x="15.5" y="15" fill="#010101" fill-opacity=".3">KCP</text><text x="15.5" y="14">KCP</text><text x="58.5" y="15" fill="#010101" fill-opacity=".3">Powered</text><text x="58.5" y="14">Powered</text></g></svg>

After

Width:  |  Height:  |  Size: 735 B

65
protocol.txt Normal file
View File

@@ -0,0 +1,65 @@
KCP PROTOCOL SPECIFICATION
1. Packet (aka. segment) Structure
KCP has only one kind of segment: both the data and control messages are
encoded into the same structure and share the same header.
The KCP packet (aka. segment) structure is as following:
0 4 5 6 8 (BYTE)
+---------------+---+---+-------+
| conv |cmd|frg| wnd |
+---------------+---+---+-------+ 8
| ts | sn |
+---------------+---------------+ 16
| una | len |
+---------------+---------------+ 24
| |
| DATA (optional) |
| |
+-------------------------------+
- conv: conversation id (32 bits integer)
The conversation id is used to identify each connection, which will not change
during the connection life-time.
It is represented by a 32 bits integer which is given at the moment the KCP
control block (aka. struct ikcpcb, or kcp object) has been created. Each
packet sent out will carry the conversation id in the first 4 bytes and a
packet from remote endpoint will not be accepted if it has a different
conversation id.
The value can be any random number, but in practice, both side between a
connection will have many KCP objects (or control block) storing in the
containers like a map or an array. A index is used as the key to look up one
KCP object from the container.
So, the higher 16 bits of conversation id can be used as caller's index while
the lower 16 bits can be used as callee's index. KCP will not handle
handshake, and the index in both side can be decided and exchanged after
connection establish.
When you receive and accept a remote packet, the local index can be extracted
from the conversation id and the kcp object which is in charge of this
connection can be find out from your map or array.
- cmd: command
- frg: fragment count
- wnd: window size
- ts: timestamp
- sn: serial number
- una: un-acknowledged serial number
# vim: set ts=4 sw=4 tw=0 noet cc=78 wrap textwidth=78 :

View File

@@ -1,8 +1,8 @@
//=====================================================================
//
// test.cpp - kcp 测试用例
// test.cpp - kcp 测试用例
//
// 说明:
// 说明:
// gcc test.cpp -o test -lstdc++
//
//=====================================================================
@@ -14,29 +14,30 @@
#include "ikcp.c"
// 模拟网络
// 模拟网络
LatencySimulator *vnet;
// 模拟网络:模拟发送一个 udp包
// 模拟网络:模拟发送一个 udp包
int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
{
int id = (int)user;
vnet->send(id, buf, len);
union { int id; void *ptr; } parameter;
parameter.ptr = user;
vnet->send(parameter.id, buf, len);
return 0;
}
// 测试用例
// 测试用例
void test(int mode)
{
// 创建模拟网络丢包率10%Rtt 60ms~125ms
// 创建模拟网络丢包率10%Rtt 60ms~125ms
vnet = new LatencySimulator(10, 60, 125);
// 创建两个端点的 kcp对象第一个参数 conv是会话编号同一个会话需要相同
// 最后一个是 user参数用来传递标识
// 创建两个端点的 kcp对象第一个参数 conv是会话编号同一个会话需要相同
// 最后一个是 user参数用来传递标识
ikcpcb *kcp1 = ikcp_create(0x11223344, (void*)0);
ikcpcb *kcp2 = ikcp_create(0x11223344, (void*)1);
// 设置kcp的下层输出这里为 udp_output模拟udp网络输出函数
// 设置kcp的下层输出这里为 udp_output模拟udp网络输出函数
kcp1->output = udp_output;
kcp2->output = udp_output;
@@ -48,29 +49,31 @@ void test(int mode)
int count = 0;
int maxrtt = 0;
// 配置窗口大小平均延迟200ms每20ms发送一个包
// 而考虑到丢包重发设置最大收发窗口为128
// 配置窗口大小平均延迟200ms每20ms发送一个包
// 而考虑到丢包重发设置最大收发窗口为128
ikcp_wndsize(kcp1, 128, 128);
ikcp_wndsize(kcp2, 128, 128);
// 判断测试用例的模式
// 判断测试用例的模式
if (mode == 0) {
// 默认模式
// 默认模式
ikcp_nodelay(kcp1, 0, 10, 0, 0);
ikcp_nodelay(kcp2, 0, 10, 0, 0);
}
else if (mode == 1) {
// 普通模式,关闭流控等
// 普通模式,关闭流控等
ikcp_nodelay(kcp1, 0, 10, 0, 1);
ikcp_nodelay(kcp2, 0, 10, 0, 1);
} else {
// 启动快速模式
// 第二个参数 nodelay-启用以后若干常规加速将启动
// 第三个参数 interval为内部处理时钟默认设置为 10ms
// 第四个参数 resend为快速重传指标设置为2
// 第五个参数 为是否禁用常规流控,这里禁止
ikcp_nodelay(kcp1, 1, 10, 2, 1);
ikcp_nodelay(kcp2, 1, 10, 2, 1);
// 启动快速模式
// 第二个参数 nodelay-启用以后若干常规加速将启动
// 第三个参数 interval为内部处理时钟默认设置为 10ms
// 第四个参数 resend为快速重传指标设置为2
// 第五个参数 为是否禁用常规流控,这里禁止
ikcp_nodelay(kcp1, 2, 10, 2, 1);
ikcp_nodelay(kcp2, 2, 10, 2, 1);
kcp1->rx_minrto = 10;
kcp1->fastresend = 1;
}
@@ -85,51 +88,51 @@ void test(int mode)
ikcp_update(kcp1, iclock());
ikcp_update(kcp2, iclock());
// 每隔 20mskcp1发送数据
// 每隔 20mskcp1发送数据
for (; current >= slap; slap += 20) {
*(IUINT32*)(buffer + 0) = index++;
*(IUINT32*)(buffer + 4) = current;
((IUINT32*)buffer)[0] = index++;
((IUINT32*)buffer)[1] = current;
// 发送上层协议包
// 发送上层协议包
ikcp_send(kcp1, buffer, 8);
}
// 处理虚拟网络检测是否有udp包从p1->p2
// 处理虚拟网络检测是否有udp包从p1->p2
while (1) {
hr = vnet->recv(1, buffer, 2000);
if (hr < 0) break;
// 如果 p2收到udp则作为下层协议输入到kcp2
// 如果 p2收到udp则作为下层协议输入到kcp2
ikcp_input(kcp2, buffer, hr);
}
// 处理虚拟网络检测是否有udp包从p2->p1
// 处理虚拟网络检测是否有udp包从p2->p1
while (1) {
hr = vnet->recv(0, buffer, 2000);
if (hr < 0) break;
// 如果 p1收到udp则作为下层协议输入到kcp1
// 如果 p1收到udp则作为下层协议输入到kcp1
ikcp_input(kcp1, buffer, hr);
}
// kcp2接收到任何包都返回回去
// kcp2接收到任何包都返回回去
while (1) {
hr = ikcp_recv(kcp2, buffer, 10);
// 没有收到包就退出
// 没有收到包就退出
if (hr < 0) break;
// 如果收到包就回射
// 如果收到包就回射
ikcp_send(kcp2, buffer, hr);
}
// kcp1收到kcp2的回射数据
// kcp1收到kcp2的回射数据
while (1) {
hr = ikcp_recv(kcp1, buffer, 10);
// 没有收到包就退出
// 没有收到包就退出
if (hr < 0) break;
IUINT32 sn = *(IUINT32*)(buffer + 0);
IUINT32 ts = *(IUINT32*)(buffer + 4);
IUINT32 rtt = current - ts;
if (sn != next) {
// 如果收到的包不连续
// 如果收到的包不连续
printf("ERROR sn %d<->%d\n", (int)count, (int)next);
return;
}
@@ -151,16 +154,16 @@ void test(int mode)
const char *names[3] = { "default", "normal", "fast" };
printf("%s mode result (%dms):\n", names[mode], (int)ts1);
printf("avgrtt=%d maxrtt=%d\n", (int)(sumrtt / count), maxrtt);
printf("avgrtt=%d maxrtt=%d tx=%d\n", (int)(sumrtt / count), (int)maxrtt, (int)vnet->tx1);
printf("press enter to next ...\n");
char ch; scanf("%c", &ch);
}
int main()
{
test(0); // 默认模式,类似 TCP正常模式无快速重传常规流控
test(1); // 普通模式,关闭流控等
test(2); // 快速模式,所有开关都打开,且关闭流控
test(0); // 默认模式,类似 TCP正常模式无快速重传常规流控
test(1); // 普通模式,关闭流控等
test(2); // 快速模式,所有开关都打开,且关闭流控
return 0;
}
@@ -175,3 +178,4 @@ fast mode result (20207ms):
avgrtt=138 maxrtt=392
*/

32
test.h
View File

@@ -83,12 +83,12 @@ static inline void isleep(unsigned long millisecond)
#include <list>
#include <vector>
// 带延迟的数据包
// 带延迟的数据包
class DelayPacket
{
public:
virtual ~DelayPacket() {
if (_ptr) delete _ptr;
if (_ptr) delete[] _ptr;
_ptr = NULL;
}
@@ -113,7 +113,7 @@ protected:
IUINT32 _ts;
};
// 均匀分布的随机数
// 均匀分布的随机数
class Random
{
public:
@@ -142,27 +142,29 @@ protected:
std::vector<int> seeds;
};
// 网络延迟模拟器
// 网络延迟模拟器
class LatencySimulator
{
public:
virtual ~LatencySimulator() {
clear();
}
// lostrate: 往返一周丢包率的百分比,默认 10%
// rttminrtt最小值默认 60
// rttmaxrtt最大值默认 125
// lostrate: 往返一周丢包率的百分比,默认 10%
// rttminrtt最小值默认 60
// rttmaxrtt最大值默认 125
LatencySimulator(int lostrate = 10, int rttmin = 60, int rttmax = 125, int nmax = 1000):
r12(100), r21(100) {
current = iclock();
this->lostrate = lostrate / 2; // 上面数据是往返丢包率单程除以2
this->lostrate = lostrate / 2; // 上面数据是往返丢包率单程除以2
this->rttmin = rttmin / 2;
this->rttmax = rttmax / 2;
this->nmax = nmax;
tx1 = tx2 = 0;
}
// 清除数据
// 清除数据
void clear() {
DelayTunnel::iterator it;
for (it = p12.begin(); it != p12.end(); it++) {
@@ -175,13 +177,15 @@ public:
p21.clear();
}
// 发送数据
// peer - 端点0/1从0发送从1接收从1发送从0接收
// 发送数据
// peer - 端点0/1从0发送从1接收从1发送从0接收
void send(int peer, const void *data, int size) {
if (peer == 0) {
tx1++;
if (r12.random() < lostrate) return;
if ((int)p12.size() >= nmax) return;
} else {
tx2++;
if (r21.random() < lostrate) return;
if ((int)p21.size() >= nmax) return;
}
@@ -197,7 +201,7 @@ public:
}
}
// 接收数据
// 接收数据
int recv(int peer, void *data, int maxsize) {
DelayTunnel::iterator it;
if (peer == 0) {
@@ -222,6 +226,10 @@ public:
return maxsize;
}
public:
int tx1;
int tx2;
protected:
IUINT32 current;
int lostrate;