Github 仓库链接: https://github.com/dcalsky/wws-socket
N 年前用 socket.io 做了一个简单的多人游戏对战服务器,当时用的 websocket 。最近发现对 socket 了解与使用并不深刻,于是从头做一个小项目,一步步加深对 TCP 数据传输的理解。
The Simplest room IM system made by Netty TCP. Inspired by @WWS.
PackageT is a TCP communication packet structure of WWS-SOCKET that includes two parts: Header and Body.
Client use socket to create connection with server and then send packet based PackageT to it. Once server validates packet successfully, it will reply a packet back.
PackageT
+---------------------------------------------------------------------+
| 20 Bytes Unlimited |
|+---------------------++--------------------------------------------+|
|| Header || Body ||
|+---------------------++--------------------------------------------+|
+---------------------------------------------------------------------+
The header of packageT has fixed 20 bytes including 4 parts. Message Type
has 2 bytes with uint16 (little-endian), body Length
has 4 bytes with uint32 (little-endian), Send Time
has 8 bytes with uint64 (little-endian) and Package Hash
has 6 bytes.
PackageT Header
+--------------------------------------------------------------------------------------+
| 2 Bytes 4 Bytes 8 Bytes 6 Bytes |
| +------------++-----------------+ +-------------------------++---------------------+ |
| |Message Type|| Body Length | | Send Time || Package Hash | |
| +------------++-----------------+ +-------------------------++---------------------+ |
+--------------------------------------------------------------------------------------+
The byte length of packet body, client/server should measure body before sending packet.
Unix millisecond timestamp when the packet sent.
Client generates a unique hash value before sending a packet and attach it to the header of packet. And then server should reply a packet with this hash in the header (except ROOM_MSG response type).
The body structure of PackageT depends on Message Type, which means different message type has corresponding body.