You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nnet/packet/packer.go

54 lines
1.1 KiB
Go

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
}