/
msgpacket.go
92 lines (71 loc) · 1.69 KB
/
msgpacket.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
package gtp
import (
"git.golaxy.org/plugins/util/binaryutil"
)
// MsgPacket 消息包
type MsgPacket struct {
Head MsgHead // 消息头
Msg Msg // 消息
}
// Read implements io.Reader
func (mp MsgPacket) Read(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
if _, err := binaryutil.ReadFrom(&bs, mp.Head); err != nil {
return bs.BytesWritten(), err
}
if mp.Msg == nil {
return bs.BytesWritten(), nil
}
if _, err := binaryutil.ReadFrom(&bs, mp.Msg); err != nil {
return bs.BytesWritten(), err
}
return bs.BytesWritten(), nil
}
// Write implements io.Writer
func (mp *MsgPacket) Write(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
if _, err := bs.WriteTo(&mp.Head); err != nil {
return bs.BytesRead(), err
}
if mp.Msg == nil {
return bs.BytesRead(), nil
}
if _, err := bs.WriteTo(mp.Msg); err != nil {
return bs.BytesRead(), err
}
return bs.BytesRead(), nil
}
// Size 大小
func (mp MsgPacket) Size() int {
n := mp.Head.Size()
if mp.Msg != nil {
n += mp.Msg.Size()
}
return n
}
// MsgPacketLen 消息包长度
type MsgPacketLen struct {
Len uint32 // 消息包长度
}
// Read implements io.Reader
func (m MsgPacketLen) Read(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
if err := bs.WriteUint32(m.Len); err != nil {
return bs.BytesWritten(), err
}
return bs.BytesWritten(), nil
}
// Write implements io.Writer
func (m *MsgPacketLen) Write(p []byte) (int, error) {
bs := binaryutil.NewBigEndianStream(p)
var err error
m.Len, err = bs.ReadUint32()
if err != nil {
return bs.BytesRead(), err
}
return bs.BytesRead(), nil
}
// Size 大小
func (MsgPacketLen) Size() int {
return binaryutil.SizeofUint32()
}