-
Notifications
You must be signed in to change notification settings - Fork 34
/
msghandler.go
57 lines (49 loc) · 1.03 KB
/
msghandler.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
package main
import (
"bytes"
"encoding/binary"
"sync"
)
// MsgQueue is global message queue
var MsgQueue chan (*msgContext)
type msgContext struct {
sess session
msg []byte
}
type handlerInterface interface {
handleMessage(ctx *msgContext) error
}
type msgHandler struct {
handlersMtx sync.RWMutex
handlers map[uint16]handlerInterface
}
func (h *msgHandler) registerHandler(msgType uint16, hi handlerInterface) error {
h.handlersMtx.Lock()
defer h.handlersMtx.Unlock()
//TODO: duplicated msgType
h.handlers[msgType] = hi
return nil
}
func (h *msgHandler) handleMessage() error {
for {
select {
case ctx := <-MsgQueue:
// TODO: parse header multi times
head := openP2PHeader{}
err := binary.Read(bytes.NewReader(ctx.msg[:openP2PHeaderSize]), binary.LittleEndian, &head)
if err != nil {
continue
}
h, ok := h.handlers[head.MainType]
if ok {
err = h.handleMessage(ctx)
if err != nil {
gLog.Println(LvERROR, err)
}
}
}
}
}
func init() {
MsgQueue = make(chan *msgContext, 1000)
}