fix: 修复 packer 共用问题。

main v0.2.0
NorthLan 2 years ago
parent f146355b96
commit 3730205022

@ -40,8 +40,10 @@ type (
session *session.Session // Session session *session.Session // Session
ngin *engine // engine ngin *engine // engine
conn net.Conn // low-level conn fd
status int32 // 连接状态 status int32 // 连接状态
conn net.Conn // low-level conn fd
packer packet.Packer // 封包、拆包器
lastMid uint64 // 最近一次消息ID lastMid uint64 // 最近一次消息ID
// TODO 考虑独立出去作为一个中间件 // TODO 考虑独立出去作为一个中间件
lastHeartbeatAt int64 // 最近一次心跳时间 lastHeartbeatAt int64 // 最近一次心跳时间
@ -59,9 +61,11 @@ type (
func newConn(server *engine, conn net.Conn) *Connection { func newConn(server *engine, conn net.Conn) *Connection {
r := &Connection{ r := &Connection{
conn: conn,
ngin: server, ngin: server,
status: StatusStart, status: StatusStart,
conn: conn,
packer: server.packerFn(),
lastHeartbeatAt: time.Now().Unix(), lastHeartbeatAt: time.Now().Unix(),
@ -189,7 +193,7 @@ func (r *Connection) write() {
} }
// packet pack data // packet pack data
p, err := r.ngin.packer.Pack(data.header, data.payload.([]byte)) p, err := r.packer.Pack(data.header, data.payload.([]byte))
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
break break
@ -222,13 +226,13 @@ func (r *Connection) read() {
return return
} }
if r.ngin.packer == nil { if r.packer == nil {
log.Errorf("unexpected error: packer is nil") log.Errorf("unexpected error: packer is nil")
return return
} }
// warning: 为性能考虑复用slice处理数据buf传入后必须要copy再处理 // warning: 为性能考虑复用slice处理数据buf传入后必须要copy再处理
packets, err := r.ngin.packer.Unpack(buf[:n]) packets, err := r.packer.Unpack(buf[:n])
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
} }

@ -42,7 +42,7 @@ type (
pipeline Pipeline // 消息管道 pipeline Pipeline // 消息管道
packer packet.Packer // 封包、拆包器 packerFn packet.NewPackerFunc // 封包、拆包器
processor Processor // 数据包处理器 processor Processor // 数据包处理器
serializer serialize.Serializer // 消息 序列化/反序列化 serializer serialize.Serializer // 消息 序列化/反序列化

@ -107,9 +107,9 @@ func WithRouter(router Router) RunOption {
} }
} }
func WithPacker(packer packet.Packer) RunOption { func WithPacker(fn packet.NewPackerFunc) RunOption {
return func(server *Server) { return func(server *Server) {
server.ngin.packer = packer server.ngin.packerFn = fn
} }
} }

@ -15,7 +15,9 @@ func TestServer(t *testing.T) {
Name: "N-Net", Name: "N-Net",
Mode: DevMode, Mode: DevMode,
}, },
WithPacker(packet.NewNNetPacker()), WithPacker(func() packet.Packer {
return packet.NewNNetPacker()
}),
WithSerializer(nil), WithSerializer(nil),
WithHeartbeatInterval(time.Hour), WithHeartbeatInterval(time.Hour),
WithProcessor(NewNNetProcessor()), WithProcessor(NewNNetProcessor()),

@ -16,4 +16,6 @@ type (
// Unpack 解包 // Unpack 解包
Unpack(data []byte) ([]IPacket, error) Unpack(data []byte) ([]IPacket, error)
} }
NewPackerFunc func() Packer
) )

Loading…
Cancel
Save