-
Notifications
You must be signed in to change notification settings - Fork 11
/
conn.go
73 lines (60 loc) · 1.04 KB
/
conn.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
package main
import (
"time"
"github.com/smallnest/ringbuffer"
"github.com/smallnest/rpcx/protocol"
)
type connection struct {
key string
buf *ringbuffer.RingBuffer
closeCallback func(err error)
parseCallBack func(key string, msg *protocol.Message)
found bool
done chan struct{}
}
func (c *connection) Start() {
for {
if !c.findFirstMsg() {
continue
}
select {
case <-c.done:
return
default:
msg, err := protocol.Read(c.buf)
if err != nil {
c.closeCallback(err)
return
}
c.parseCallBack(c.key, msg)
}
}
}
const magicNumber byte = 0x08
func (c *connection) findFirstMsg() bool {
if c.found {
return true
}
buf := c.buf.Bytes()
if len(buf) == 0 {
time.Sleep(time.Millisecond)
return false
}
if buf[0] == magicNumber {
c.found = true
return true
}
var index = len(buf) - 1
for i, c := range buf {
if c == magicNumber {
index = i - 1
break
}
}
data := make([]byte, index)
c.buf.Read(data)
return false
}
func (c *connection) Close() {
close(c.done)
}