forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler_callback.go
86 lines (62 loc) · 1.66 KB
/
handler_callback.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
package cellnet
import (
"fmt"
)
type CallbackHandler struct {
userCallback func(*Event)
}
func (self *CallbackHandler) Call(ev *Event) {
self.userCallback(ev)
}
func NewCallbackHandler(userCallback func(*Event)) EventHandler {
return &CallbackHandler{
userCallback: userCallback,
}
}
type RegisterMessageContext struct {
*MessageMeta
}
// 注册消息处理回调
func RegisterMessage(p Peer, msgName string, userCallback func(*Event)) *RegisterMessageContext {
return RegisterHandler(p, msgName, NewCallbackHandler(userCallback))
}
// 注册消息处理的一系列Handler, 当有队列时, 投放到队列
func RegisterHandler(p Peer, msgName string, handlers ...EventHandler) *RegisterMessageContext {
if p == nil {
return nil
}
meta := MessageMetaByName(msgName)
if meta == nil {
panic(fmt.Sprintf("message register failed, name not found: %s", msgName))
}
if p.Queue() != nil {
p.AddChainRecv(NewHandlerChain(
NewMatchMsgIDHandler(meta.ID),
StaticDecodePacketHandler(),
NewQueuePostHandler(p.Queue(), handlers...),
))
} else {
p.AddChainRecv(NewHandlerChain(
NewMatchMsgIDHandler(meta.ID),
StaticDecodePacketHandler(),
handlers,
))
}
return &RegisterMessageContext{MessageMeta: meta}
}
// 直接注册回调
func RegisterRawHandler(p Peer, msgName string, handlers ...EventHandler) *RegisterMessageContext {
if p == nil {
return nil
}
meta := MessageMetaByName(msgName)
if meta == nil {
panic(fmt.Sprintf("message register failed, %s", msgName))
}
p.AddChainRecv(NewHandlerChain(
NewMatchMsgIDHandler(meta.ID),
StaticDecodePacketHandler(),
handlers,
))
return &RegisterMessageContext{MessageMeta: meta}
}