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.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.