Files
bl/common/socket/codec/SocketCodec_Tomee.go
昔念 9a802ce948 ```
fix(socket): 调整连接读超时与数据包解析逻辑

- 在 `OnOpen` 中为连接设置 3 秒读超时
- 简化 `handleTcp` 中不完整数据包的处理流程,移除手动唤醒逻辑
- 修改 `SocketCodec_Tomee.go` 中最大包体长度限制从 10MB 降至 10KB
- 修复 `Decode` 方法中未处理 `c.Next` 错误的问题
- 更新 .gitignore 忽略重复的 logic/logic1 文件路径
```
2025-11-03 05:46:13 +08:00

74 lines
1.5 KiB
Go

package codec
import (
"encoding/binary"
"errors"
"io"
"github.com/panjf2000/gnet/v2"
)
var ErrIncompletePacket = errors.New("incomplete packet")
const maxBodyLen = 10 * 1024 // 业务最大包体长度,按需调整
// TomeeSocketCodec 协议格式:
//
// * 0 4
// * +-----------+
// * | body len |
// * +-----------+
// * | |
// * + +
// * | body bytes|
// * + +
// * | ... ... |
// * +-----------+
type TomeeSocketCodec struct{}
var _ SocketCodec = (*TomeeSocketCodec)(nil)
func NewTomeeSocketCodec() *TomeeSocketCodec {
return &TomeeSocketCodec{}
}
func (codec TomeeSocketCodec) Encode(buf []byte) ([]byte, error) {
bodyLen := len(buf)
data := make([]byte, 4+bodyLen)
// 写入4字节的包长度
binary.BigEndian.PutUint32(data[:4], uint32(bodyLen))
// 写入包体
copy(data[4:], buf)
return data, nil
}
func (codec TomeeSocketCodec) Decode(c gnet.Conn) ([]byte, error) {
// handle(c)
// 先读取4字节的包长度
lenBuf, err := c.Peek(4)
if err != nil {
if errors.Is(err, io.ErrShortBuffer) {
return nil, ErrIncompletePacket
}
return nil, err
}
bodyLen := binary.BigEndian.Uint32(lenBuf)
if bodyLen > maxBodyLen {
return nil, errors.New("packet body exceeds max length")
}
if c.InboundBuffered() < int(bodyLen) {
return nil, ErrIncompletePacket
}
// 提取包体
body, err := c.Next(int(bodyLen))
return body, err
}