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
2 years ago
|
package protocol
|
||
2 years ago
|
|
||
|
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
|
||
|
}
|
||
2 years ago
|
NNetPacket struct {
|
||
2 years ago
|
Header
|
||
|
Data []byte // 原始数据
|
||
|
}
|
||
|
)
|
||
|
|
||
2 years ago
|
func newPacket(typ Type) *NNetPacket {
|
||
|
return &NNetPacket{
|
||
2 years ago
|
Header: Header{
|
||
|
PacketType: typ,
|
||
|
MessageHeader: MessageHeader{},
|
||
|
},
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
func (p *NNetPacket) GetHeader() interface{} {
|
||
2 years ago
|
return p.Header
|
||
|
}
|
||
|
|
||
2 years ago
|
func (p *NNetPacket) GetLen() uint64 {
|
||
|
return uint64(p.Length)
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
func (p *NNetPacket) GetBody() []byte {
|
||
2 years ago
|
return p.Data
|
||
|
}
|
||
|
|
||
2 years ago
|
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]",
|
||
2 years ago
|
p.PacketType, p.Length, p.MsgType, p.ID, p.Route, p.compressed, string(p.Data), hex.EncodeToString(p.Data))
|
||
|
}
|