feat(proto): 自 go-hua 迁入长度前缀封包协议编解码
- 8 字节头(4 字节 ID/校验 + 4 字节长度, 小端序) + CRC32 校验版本 - 附测试、examples/proto 例程与包 README(含 Decode reader 复用告诫)
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
// proto 包示例:通用封包协议(消息头 8 字节 = ID 4 字节 + 长度 4 字节,小端序),支持 CRC32 校验版本
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"git.zeroonesoft.cn/golib/zogo/proto"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
// ===== 普通封包:Encode / Decode =====
|
||||
go func() {
|
||||
data, err := proto.Encode([]byte("hello proto"))
|
||||
if err != nil {
|
||||
fmt.Println("Encode:", err)
|
||||
return
|
||||
}
|
||||
client.Write(data)
|
||||
}()
|
||||
|
||||
buf, err := proto.Decode(bufio.NewReader(server))
|
||||
fmt.Println("Decode:", string(buf), "错误:", err)
|
||||
|
||||
// ===== CRC32 校验封包:EncodeCrc32 / DecodeCrc32 =====
|
||||
go func() {
|
||||
data, err := proto.EncodeCrc32([]byte("hello crc32"))
|
||||
if err != nil {
|
||||
fmt.Println("EncodeCrc32:", err)
|
||||
return
|
||||
}
|
||||
client.Write(data)
|
||||
}()
|
||||
|
||||
buf, err = proto.DecodeCrc32(bufio.NewReader(server))
|
||||
fmt.Println("DecodeCrc32:", string(buf), "错误:", err)
|
||||
|
||||
// 实际 TCP 服务中的用法:
|
||||
// reader := bufio.NewReader(conn)
|
||||
// for {
|
||||
// data, err := proto.Decode(reader) // 阻塞读到完整一帧
|
||||
// handle(data)
|
||||
// }
|
||||
}
|
||||
Reference in New Issue
Block a user