-
Notifications
You must be signed in to change notification settings - Fork 194
/
protocol.go
42 lines (34 loc) · 970 Bytes
/
protocol.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
package main
import (
"encoding/binary"
"github.com/Allenxuxu/gev"
"github.com/Allenxuxu/ringbuffer"
"github.com/gobwas/pool/pbytes"
)
const exampleHeaderLen = 4
type ExampleProtocol struct{}
func (d *ExampleProtocol) UnPacket(c *gev.Connection, buffer *ringbuffer.RingBuffer) (interface{}, []byte) {
if buffer.VirtualLength() > exampleHeaderLen {
buf := pbytes.GetLen(exampleHeaderLen)
defer pbytes.Put(buf)
_, _ = buffer.VirtualRead(buf)
dataLen := binary.BigEndian.Uint32(buf)
if buffer.VirtualLength() >= int(dataLen) {
ret := make([]byte, dataLen)
_, _ = buffer.VirtualRead(ret)
buffer.VirtualFlush()
return nil, ret
} else {
buffer.VirtualRevert()
}
}
return nil, nil
}
func (d *ExampleProtocol) Packet(c *gev.Connection, data interface{}) []byte {
dd := data.([]byte)
dataLen := len(dd)
ret := make([]byte, exampleHeaderLen+dataLen)
binary.BigEndian.PutUint32(ret, uint32(dataLen))
copy(ret[4:], dd)
return ret
}