wip: 重弄一下编码解码,封包解包。
parent
5779bb7989
commit
6ec0070ebe
@ -1,10 +1,8 @@
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/panjf2000/ants/v2 v2.6.0 h1:xOSpw42m+BMiJ2I33we7h6fYzG4DAlpE1xyI7VS2gxU=
|
||||
github.com/panjf2000/ants/v2 v2.6.0/go.mod h1:cU93usDlihJZ5CfRGNDYsiBYvoilLvBF5Qp/BT2GNRE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
|
||||
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
||||
|
@ -0,0 +1,53 @@
|
||||
package packet
|
||||
|
||||
type Packer interface {
|
||||
// Pack 从原始raw bytes创建一个用于网络传输的 packet.Packet 结构
|
||||
Pack(typ Type, data []byte) ([]byte, error)
|
||||
|
||||
// Unpack 解包
|
||||
Unpack(data []byte) (*Packet, error)
|
||||
}
|
||||
|
||||
type DefaultPacker struct {
|
||||
}
|
||||
|
||||
// Codec constants.
|
||||
const (
|
||||
headLength = 4
|
||||
maxPacketSize = 64 * 1024
|
||||
)
|
||||
|
||||
func NewDefaultPacker() Packer {
|
||||
return &DefaultPacker{}
|
||||
}
|
||||
|
||||
func (d *DefaultPacker) Pack(typ Type, data []byte) ([]byte, error) {
|
||||
if typ < Handshake || typ > Kick {
|
||||
return nil, ErrWrongPacketType
|
||||
}
|
||||
|
||||
p := &Packet{Type: typ, Length: uint32(len(data))}
|
||||
buf := make([]byte, p.Length+headLength)
|
||||
|
||||
// header
|
||||
buf[0] = byte(p.Type)
|
||||
copy(buf[1:headLength], d.intToBytes(p.Length))
|
||||
|
||||
// body
|
||||
copy(buf[headLength:], data)
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// Encode packet data length to bytes(Big end)
|
||||
func (d *DefaultPacker) intToBytes(n uint32) []byte {
|
||||
buf := make([]byte, 3)
|
||||
buf[0] = byte((n >> 16) & 0xFF)
|
||||
buf[1] = byte((n >> 8) & 0xFF)
|
||||
buf[2] = byte(n & 0xFF)
|
||||
return buf
|
||||
}
|
||||
|
||||
func (d *DefaultPacker) Unpack(data []byte) (*Packet, error) {
|
||||
// header
|
||||
}
|
Loading…
Reference in New Issue