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.
95 lines
1.8 KiB
Go
95 lines
1.8 KiB
Go
package protocol
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"fmt"
|
|
)
|
|
|
|
// Type 数据帧类型,如:握手,心跳,数据 等
|
|
type Type byte
|
|
|
|
const (
|
|
// Unknown 未知包类型,无意义
|
|
Unknown Type = iota
|
|
|
|
// Handshake 握手数据(服务端主动发起)
|
|
Handshake = 0x01
|
|
|
|
// HandshakeAck 握手回复(客户端回复)
|
|
HandshakeAck = 0x02
|
|
|
|
// Heartbeat 心跳(服务端发起)
|
|
Heartbeat = 0x03
|
|
|
|
// Data 数据传输
|
|
Data = 0x04
|
|
|
|
// Kick 服务端主动断开连接
|
|
Kick = 0x05
|
|
)
|
|
|
|
type MsgType byte
|
|
|
|
// Message types
|
|
const (
|
|
Request MsgType = 0x00
|
|
Notify = 0x01
|
|
Response = 0x02
|
|
Push = 0x03
|
|
)
|
|
|
|
var msgTypes = map[MsgType]string{
|
|
Request: "Request",
|
|
Notify: "Notify",
|
|
Response: "Response",
|
|
Push: "Push",
|
|
}
|
|
|
|
func (t MsgType) String() string {
|
|
return msgTypes[t]
|
|
}
|
|
|
|
type (
|
|
Header struct {
|
|
PacketType Type // 数据帧 类型
|
|
Length uint32 // 数据长度
|
|
MessageHeader // 消息头
|
|
}
|
|
MessageHeader struct {
|
|
MsgType MsgType // message type (flag)
|
|
ID uint64 // unique id, zero while notify mode
|
|
Route string // route for locating service
|
|
compressed bool // if message compressed
|
|
}
|
|
NNetPacket struct {
|
|
Header
|
|
Data []byte // 原始数据
|
|
}
|
|
)
|
|
|
|
func newPacket(typ Type) *NNetPacket {
|
|
return &NNetPacket{
|
|
Header: Header{
|
|
PacketType: typ,
|
|
MessageHeader: MessageHeader{},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (p *NNetPacket) GetHeader() interface{} {
|
|
return p.Header
|
|
}
|
|
|
|
func (p *NNetPacket) GetLen() uint64 {
|
|
return uint64(p.Length)
|
|
}
|
|
|
|
func (p *NNetPacket) GetBody() []byte {
|
|
return p.Data
|
|
}
|
|
|
|
func (p *NNetPacket) String() string {
|
|
return fmt.Sprintf("NNetPacket[Type: %d, Len: %d] Message[Type: %s, ID: %d, Route: %s, Compressed: %v] BodyStr: [%s], BodyHex: [%s]",
|
|
p.PacketType, p.Length, p.MsgType, p.ID, p.Route, p.compressed, string(p.Data), hex.EncodeToString(p.Data))
|
|
}
|