Updated EN_Cooperate With Tcp Server (markdown)

winlin 2017-02-17 10:15:30 +08:00
parent dd210b4ea2
commit a16346cf03

@ -1,22 +1,22 @@
## Integrate with TCP Server
在使用 KCP时你可以用在你 TCP的基础上再登陆时服务端返回 UDP端口和密钥客户端通过 TCP收到以后向服务端的 UDP端口每隔一秒重复发送包含握手信息直到服务端返回成功或者失败。服务端通过 UDP传上来的密钥得知该客户端 sockaddr对应的 TCP连接这样就建立 TCP连接到 UDP连接的映射关系。为了保持连接和 NAT出口映射客户端一般需要每 60秒就发送一个 UDP心跳服务端收到后回复客户端再在这个 UDP连接的基础上增加调用 KCP的逻辑实现快速可靠传输这样一套 TCP/UDP两用的传输系统就建立了。
When integrating KCP to TCP server, when client handshake to server, server can response the port of UDP(Maybe with other information, such as security key), then client can try UDP handshake with server(Maybe with other informations, for instance, security key or TCP id). Finally, both TCP and UDP channel are ready, and server can find out about the map between TCP and UDP for a client. User can use UDP first, then fallback to TCP if has any problem.
可以参考下述例子:
For example:
1. 客户端链接tcp服务端为该tcp链接分配一个整数id作为标识。
2. 登录后服务端给客户端发送udp握手信息包括自己的udp端口用户的tcp标识id32位随机数key
3. 客户端给服务端udp地址发送握手信息把刚才服务端发过来的(id, key) 发送给服务端。
4. 服务端确认udp握手并且记录该用户udp远端地址
5. 以后客户端和服务端udp通信每个包都包含id, key
6. 服务端用客户端发上来的idkey确认用户身份并对比远端地址confirm是一个合法用户。
1. Client connect to TCP server, the `id` for this client is generated as identify on server-side.
2. Server response client, including `port` of UDP, `id`, a 32 bits security `key`.
3. Client send UDP packet to server, with (`id` and `key`).
4. Server send UDP packet to client, map the TCP and UDP as a pair.
5. Client try UDP, each UDP packet carry (`id` and `key`).
6. Server can validate the client by (`id and `key).
注意:为了保持 NAT映射关系UDP需要每隔 60秒就像服务器 ping一次。同时为了防止出口地址改变NAT映射改变或者移动设备切换基站可以使用重连或者UDP重绑定但是在 3G,2G,EDGE下面出口改变TCP也就断了所以简单重连也没问题
> Remark: Client should send ping message for UDP to keep-alive, or NAT may change the address or port. Client can also reconnect when network changed, for example, the mobile device change base station.
客户端和原有的TCP连接对象稍微封装一下就得到一个类似
Client can use a general API like:
`connection.send(channel, data, size)`
的接口channel=0时使用原有tcp发送channel=1时使用kcp发送channel=2时使用裸的udp发送。三个channel同时工作适配不同情况。服务端接口也类似。
When channel is 0, send data over TCP; over KCP when channel is 1; use original UDP when channel is 2. It's similar on server-side.
中国的网络情况比较特殊,会存在有些网络 UDP连接不上的情况因此都是先连接 TCP然后试图 UDPUDP不通的情况下退回 TCP也能正常游戏一旦 TCP断开则认为 UDP也断开了。
In china, it's recommented to try UDP, and fallback to TCP when failed.