-
Notifications
You must be signed in to change notification settings - Fork 17
/
tpacket.go
109 lines (89 loc) · 2.21 KB
/
tpacket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package turbo
import (
"bytes"
"encoding/binary"
)
type Compress int8
//packet的包头部分
type PacketHeader struct {
Opaque uint32 //请求的seqId
CmdType uint8 //类型
Version int16 //协议的版本号
Extension int64 //扩展预留字段
BodyLen int32 //body的长度
}
func MarshalHeader(header PacketHeader, bodyLen int32) *bytes.Buffer {
b := make([]byte, 0, PACKET_HEAD_LEN+bodyLen)
buff := bytes.NewBuffer(b)
//写入包头长度
Write(buff, binary.BigEndian, header.Opaque)
Write(buff, binary.BigEndian, header.CmdType)
Write(buff, binary.BigEndian, header.Version)
Write(buff, binary.BigEndian, header.Extension)
Write(buff, binary.BigEndian, bodyLen)
return buff
}
func UnmarshalHeader(r *bytes.Reader) (PacketHeader, error) {
header := PacketHeader{}
err := Read(r, binary.BigEndian, &(header.Opaque))
if nil != err {
return header, err
}
err = Read(r, binary.BigEndian, &(header.CmdType))
if nil != err {
return header, err
}
err = Read(r, binary.BigEndian, &(header.Version))
if nil != err {
return header, err
}
err = Read(r, binary.BigEndian, &(header.Extension))
if nil != err {
return header, err
}
err = Read(r, binary.BigEndian, &(header.BodyLen))
if nil != err {
return header, err
}
return header, nil
}
//-----------请求的packet
type Packet struct {
Header PacketHeader
Data []byte
PayLoad interface{}
//packet的回调
OnComplete func(err error)
}
func NewPacket(cmdtype uint8, data []byte) *Packet {
h := PacketHeader{Opaque: 0, CmdType: cmdtype, BodyLen: int32(len(data))}
return &Packet{Header: h,
Data: data}
}
func (self *Packet) Reset() {
self.Header.Opaque = 0
}
func NewRespPacket(opaque uint32, cmdtype uint8, data []byte) *Packet {
p := NewPacket(cmdtype, data)
p.Header.Opaque = opaque
return p
}
func (self *Packet) Marshal() []byte {
dl := 0
if nil != self.Data {
dl = len(self.Data)
}
buff := MarshalHeader(self.Header, int32(dl))
buff.Write(self.Data)
return buff.Bytes()
}
// TContext 处理的上下文
//处理器
type THandler func(ctx *TContext) error
//接受消息
type IOHandler func(message Packet, err error)
type TContext struct {
Client *TClient
Message *Packet
Err error //上下文的错误
}