-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
90 lines (78 loc) · 1.96 KB
/
reader.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
package net4g
import (
"bytes"
"github.com/carsonsx/log4g"
"runtime/debug"
"time"
)
func IsHeartbeatData(data []byte) bool {
return len(data) == len(NetConfig.HeartbeatData) && bytes.Equal(data, NetConfig.HeartbeatData)
}
type NetReader interface {
Read(after func(data []byte) bool)
}
func newNetReader(conn NetConn, serializer Serializer, dispatchers []*Dispatcher, hub NetHub) NetReader {
reader := new(netReader)
reader.conn = conn
reader.serializer = serializer
reader.dispatchers = dispatchers
reader.hub = hub
return reader
}
type netReader struct {
conn NetConn
serializer Serializer
dispatchers []*Dispatcher
hub NetHub
}
func (r *netReader) Read(prehandler func(data []byte) bool) {
for {
data, err := r.conn.Read()
if err != nil {
r.conn.Close()
break
}
r.conn.Session().Set(SESSION_CONNECT_LAST_READ_TIME, time.Now())
r.process(data, prehandler)
}
}
func (r *netReader) process(raw []byte, prehandler func(data []byte) bool) {
// safe the user handler to avoid the whole server down
defer func() {
if r := recover(); r != nil {
log4g.Error("********************* Reader Panic *********************")
log4g.Error(r)
log4g.Error(string(debug.Stack()))
log4g.Error("********************* Reader Panic *********************")
}
}()
if prehandler != nil {
if !prehandler(raw) {
return
}
}
rp := new(RawPack)
var err error
rp.Id, rp.Type, rp.Data, err = r.serializer.DeserializeId(raw)
if err != nil {
return
}
var h interface{}
var v interface{}
if NeedDeserialize(r.dispatchers, rp.Type) {
h, v, err = r.serializer.DeserializeData(rp.Data, rp.Type)
if err != nil {
return
}
} else {
log4g.Debug("no need deserialize for %v", rp.Type)
}
if rp.Type != nil {
log4g.Debug("dispatching %v", rp.Type)
} else if rp.Id != nil {
log4g.Debug("dispatching %v", rp.Id)
} else {
log4g.Debug("dispatching...")
}
Dispatch(r.dispatchers, newNetAgent(r.hub, r.conn, rp, v, h, r.serializer))
}