feat(proto): 自 go-hua 迁入长度前缀封包协议编解码
- 8 字节头(4 字节 ID/校验 + 4 字节长度, 小端序) + CRC32 校验版本 - 附测试、examples/proto 例程与包 README(含 Decode reader 复用告诫)
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
# proto
|
||||
|
||||
长度前缀封包协议的编解码:8 字节头(4 字节 ID/校验 + 4 字节长度,小端序),
|
||||
支持 CRC32 校验版本,配合 `bufio.Reader` 使用。
|
||||
|
||||
> 迁移自 go-hua/proto,代码保持原样。
|
||||
|
||||
## 帧格式
|
||||
|
||||
```
|
||||
普通版: + id/流ID (4) + length (4) + data (length) + 小端序
|
||||
CRC32 版:+ id (4) + length (4) + crc32 (4) + data (length) + 小端序
|
||||
```
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
|
||||
"git.zeroonesoft.cn/golib/zogo/proto"
|
||||
)
|
||||
|
||||
// 发送端
|
||||
wire, _ := proto.Encode([]byte("payload")) // 另有 EncodeCrc32
|
||||
conn.Write(wire)
|
||||
|
||||
// 接收端(reader 需为 *bufio.Reader,可跨帧复用)
|
||||
r := bufio.NewReader(conn)
|
||||
data, err := proto.Decode(r) // 另有 DecodeCrc32(校验失败返回错误)
|
||||
```
|
||||
|
||||
完整可运行例程:[examples/proto/main.go](../examples/proto/main.go)
|
||||
|
||||
## 注意
|
||||
|
||||
- `Decode` 会阻塞直到读满一帧;reader 请与连接同生命周期复用,勿每帧新建
|
||||
(缓冲中多读的字节会丢失——与本仓库 `frame` 包迁移前问题同理)。
|
||||
- CRC32 版本与非校验版本的头部布局不同,两端必须约定同一种。
|
||||
Reference in New Issue
Block a user