forked from siddontang/mixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacketio.go
102 lines (80 loc) · 1.75 KB
/
packetio.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
package mysql
import (
"bufio"
"fmt"
"io"
"net"
)
type PacketIO struct {
rb *bufio.Reader
wb io.Writer
Sequence uint8
}
func NewPacketIO(conn net.Conn) *PacketIO {
p := new(PacketIO)
p.rb = bufio.NewReaderSize(conn, 1024)
p.wb = conn
p.Sequence = 0
return p
}
func (p *PacketIO) ReadPacket() ([]byte, error) {
header := []byte{0, 0, 0, 0}
if _, err := io.ReadFull(p.rb, header); err != nil {
return nil, ErrBadConn
}
length := int(uint32(header[0]) | uint32(header[1])<<8 | uint32(header[2])<<16)
if length < 1 {
return nil, fmt.Errorf("invalid payload length %d", length)
}
sequence := uint8(header[3])
if sequence != p.Sequence {
return nil, fmt.Errorf("invalid sequence %d != %d", sequence, p.Sequence)
}
p.Sequence++
data := make([]byte, length)
if _, err := io.ReadFull(p.rb, data); err != nil {
return nil, ErrBadConn
} else {
if length < MaxPayloadLen {
return data, nil
}
var buf []byte
buf, err = p.ReadPacket()
if err != nil {
return nil, ErrBadConn
} else {
return append(data, buf...), nil
}
}
}
//data already have header
func (p *PacketIO) WritePacket(data []byte) error {
length := len(data) - 4
for length >= MaxPayloadLen {
data[0] = 0xff
data[1] = 0xff
data[2] = 0xff
data[3] = p.Sequence
if n, err := p.wb.Write(data[:4+MaxPayloadLen]); err != nil {
return ErrBadConn
} else if n != (4 + MaxPayloadLen) {
return ErrBadConn
} else {
p.Sequence++
length -= MaxPayloadLen
data = data[MaxPayloadLen:]
}
}
data[0] = byte(length)
data[1] = byte(length >> 8)
data[2] = byte(length >> 16)
data[3] = p.Sequence
if n, err := p.wb.Write(data); err != nil {
return ErrBadConn
} else if n != len(data) {
return ErrBadConn
} else {
p.Sequence++
return nil
}
}