-
Notifications
You must be signed in to change notification settings - Fork 193
/
protocol.go
44 lines (35 loc) · 969 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
43
44
package gev
import (
"github.com/Allenxuxu/ringbuffer"
)
var _ Protocol = &DefaultProtocol{}
// Protocol 自定义协议编解码接口
type Protocol interface {
UnPacket(c *Connection, buffer *ringbuffer.RingBuffer) (interface{}, []byte)
Packet(c *Connection, data interface{}) []byte
}
// DefaultProtocol 默认 Protocol
type DefaultProtocol struct{}
// UnPacket 拆包
func (d *DefaultProtocol) UnPacket(c *Connection, buffer *ringbuffer.RingBuffer) (interface{}, []byte) {
s, e := buffer.PeekAll()
if len(e) > 0 {
size := len(s) + len(e)
userBuffer := *c.UserBuffer()
if size > cap(userBuffer) {
userBuffer = make([]byte, size)
*c.UserBuffer() = userBuffer
}
copy(userBuffer, s)
copy(userBuffer[len(s):], e)
buffer.RetrieveAll()
return nil, userBuffer[:size]
} else {
buffer.RetrieveAll()
return nil, s
}
}
// Packet 封包
func (d *DefaultProtocol) Packet(c *Connection, data interface{}) []byte {
return data.([]byte)
}