forked from huskar-t/melody
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
80 lines (73 loc) · 1.46 KB
/
hub.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
package melody
import (
"sync"
"sync/atomic"
)
var nodata = struct{}{}
type hub struct {
sessions map[*Session]struct{}
broadcast chan *envelope
register chan *Session
unregister chan *Session
exit chan *envelope
status uint32
open bool
rwMutex *sync.RWMutex
}
func newHub() *hub {
return &hub{
sessions: make(map[*Session]struct{}),
broadcast: make(chan *envelope),
register: make(chan *Session),
unregister: make(chan *Session),
exit: make(chan *envelope),
status: StatusNormal,
rwMutex: &sync.RWMutex{},
}
}
func (h *hub) run() {
for {
select {
case s := <-h.register:
h.rwMutex.Lock()
h.sessions[s] = nodata
h.rwMutex.Unlock()
case s := <-h.unregister:
if _, ok := h.sessions[s]; ok {
h.rwMutex.Lock()
delete(h.sessions, s)
h.rwMutex.Unlock()
}
case m := <-h.broadcast:
h.rwMutex.RLock()
for s := range h.sessions {
if m.filter != nil {
if m.filter(s) {
s.writeMessage(m)
}
} else {
s.writeMessage(m)
}
}
h.rwMutex.RUnlock()
case m := <-h.exit:
h.rwMutex.Lock()
for s := range h.sessions {
s.writeMessage(m)
delete(h.sessions, s)
s.Close()
}
atomic.StoreUint32(&h.status, StatusStop)
h.rwMutex.Unlock()
return
}
}
}
func (h *hub) closed() bool {
return atomic.LoadUint32(&h.status) == StatusStop
}
func (h *hub) len() int {
h.rwMutex.RLock()
defer h.rwMutex.RUnlock()
return len(h.sessions)
}