forked from Allenxuxu/gev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.go
55 lines (44 loc) · 1.01 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
package protobuf
import (
"github.com/Allenxuxu/gev"
"github.com/Allenxuxu/ringbuffer"
"github.com/gobwas/pool/pbytes"
)
// Message 数据帧定义
type Message struct {
Len uint32
TypeLen uint16
Type string
Data []byte
}
// Protocol protobuf
type Protocol struct {
}
// New 创建 protobuf Protocol
func New() *Protocol {
return &Protocol{}
}
// UnPacket ...
func (p *Protocol) UnPacket(c *gev.Connection, buffer *ringbuffer.RingBuffer) (ctx interface{}, out []byte) {
if buffer.Length() > 6 {
length := int(buffer.PeekUint32())
if buffer.Length() >= length+4 {
buffer.Retrieve(4)
typeLen := int(buffer.PeekUint16())
buffer.Retrieve(2)
typeByte := pbytes.GetLen(typeLen)
_, _ = buffer.Read(typeByte)
dataLen := length - 2 - typeLen
data := make([]byte, dataLen)
_, _ = buffer.Read(data)
out = data
ctx = string(typeByte)
pbytes.Put(typeByte)
}
}
return
}
// Packet ...
func (p *Protocol) Packet(c *gev.Connection, data interface{}) []byte {
return data.([]byte)
}