# 快递项目socket协议protobuf定义 ## 1. 概述 * 本项目前后端使用 kcp 协议通讯 [KCP - A Fast and Reliable ARQ Protocol](https://github.com/skywind3000/kcp) ## 2. 消息 * 消息是前后端通讯的内容的封装 ### 2.1 消息格式: * 消息是拼接的二进制流 * 消息由 4 段数据拼接而成, `act` + `type` + `body length` + `body` * act: 单字节(byte), 协议号, 见下文的act定义, 根据`act`将`body`映射到对应的数据对象 * type: 单字节(byte), 定义了`body`的类型, 目前支持两种`(0=json;1=protobuf)` * body length: 双字节(short), **大端序**, 对应的是`body`的数据长度, 可以避免保证数据读取的完整性 * body: 消息正文 ### 2.1 消息读取逻辑 * 读取消息有两种选择 * 一种是使用kcp提供的read方法, 这种比较方便, 理论上应该也是没有问题的 * 读取第一个字节, 拿到act * 读取第二个字节, 拿到type * 读取第四个字节到结尾处, 拿到消息正文 * 另一种是自已实现读消息逻辑, 读取方法如下: * 读取一个字节, 拿到act * 读取一个字节, 拿到type * 读取两个字节, 按大端序写入short, 拿到body length * 读取 body length 个字节, 写入消息正文 ## 3. 消息正文 ### 3.1 act类别 * `c -> s` 表示客户端给服务器的消息 * `s -> c` 表示服务器器给客户端的消息 * `c -> s` 消息中, 带有 `request` 的消息, 服务器都有响应一个对应的 `response` 消息 * `notify`消息, 表示客户端通知服务器某些行为, 服务器知道就行了, 不需要返回任何数据 * `push` 消息, 表示服务器通知客户端某些行为, 客户端需要 ### 3.2 act定义 | 协议号 | message | 方向 | 备注 | | --- | --- | --- | --- | | 4 | SYN | c -> s | 客户端SYN请求 | | 4 | SYN | s -> c| 服务器响应SYN请求 | | 5 | CloseNotify | c -> s | 客户端关闭连接 | | 5 | ClosePush | s -> c | 服务器关闭用户连接 | | 10 | LoginRequest | c -> s | 客户端请求登陆 | | 11 | LoginResponse | s -> c | 服务器响应登陆请求 | | 12 | HeartbeatRequest | c -> s | 客户端心跳 | | 13 | HeartbeatResponse | s -> c | 服务器心跳 | | 100 | LobbyJoinPush | s -> c | 用户加入大厅 | | 101 | LobbyLeavePush | s -> c | 用户离开大厅 | | 120 | RoomCreateRequest | c -> s | 客户端请求创建房间 | | 121 | RoomCreateResponse | s -> c | 服务器响应创建房间请求 | | 122 | RoomJoinRequest | c -> s | 客户端请求加入房间 | | 123 | RoomJoinResponse | s -> c | 服务器响应加入房间请求 | | 124 | RoomJoinPush | s -> c | 服务端推送用户加入房间消息 | | 125 | RoomLeaveRequest | c -> s | 客户端请求退出房间 | | 126 | RoomLeaveResponse | s -> c | 服务器响应退出房间 | | 127 | RoomLeavePush | s -> c | 服务器推送用户离开房间消息 | | 150 | RestoreRequest | c -> s | 客户端请求恢复数据 | | 151 | RestoreResponse | s -> c | 服务器响应当前状态 | | 152 | SyncRequest | c -> s | 客户端同步数据 | | 153 | SyncResponse | s -> c | 服务器响应同步结果 | | 154 | SyncPush | s -> c | 服务器通知客户端想要他人的同步数据 | | 155 | MasterPush | s -> c | 服务器合并lockStep的消息给master | | 156 | MasterNotify | c -> s | master通知服务器广播数据给follow | | 157 | MasterStoreNotify | c -> s | master存储状态 | | 158 | MasterLoadRequest | c -> s | master读取状态 | | 159 | MasterLoadResponse | s -> c | 服务器响应master状态 |