-
Notifications
You must be signed in to change notification settings - Fork 366
/
hub.go
126 lines (101 loc) · 1.93 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package melody
import (
"sync"
"sync/atomic"
)
type sessionSet struct {
mu sync.RWMutex
members map[*Session]struct{}
}
func (ss *sessionSet) add(s *Session) {
ss.mu.Lock()
defer ss.mu.Unlock()
ss.members[s] = struct{}{}
}
func (ss *sessionSet) del(s *Session) {
ss.mu.Lock()
defer ss.mu.Unlock()
delete(ss.members, s)
}
func (ss *sessionSet) clear() {
ss.mu.Lock()
defer ss.mu.Unlock()
ss.members = make(map[*Session]struct{})
}
func (ss *sessionSet) each(cb func(*Session)) {
ss.mu.RLock()
defer ss.mu.RUnlock()
for s := range ss.members {
cb(s)
}
}
func (ss *sessionSet) len() int {
ss.mu.RLock()
defer ss.mu.RUnlock()
return len(ss.members)
}
func (ss *sessionSet) all() []*Session {
ss.mu.RLock()
defer ss.mu.RUnlock()
s := make([]*Session, 0, len(ss.members))
for k := range ss.members {
s = append(s, k)
}
return s
}
type hub struct {
sessions sessionSet
broadcast chan envelope
register chan *Session
unregister chan *Session
exit chan envelope
open atomic.Bool
}
func newHub() *hub {
return &hub{
sessions: sessionSet{
members: make(map[*Session]struct{}),
},
broadcast: make(chan envelope),
register: make(chan *Session),
unregister: make(chan *Session),
exit: make(chan envelope),
}
}
func (h *hub) run() {
h.open.Store(true)
loop:
for {
select {
case s := <-h.register:
h.sessions.add(s)
case s := <-h.unregister:
h.sessions.del(s)
case m := <-h.broadcast:
h.sessions.each(func(s *Session) {
if m.filter == nil {
s.writeMessage(m)
} else if m.filter(s) {
s.writeMessage(m)
}
})
case m := <-h.exit:
h.open.Store(false)
h.sessions.each(func(s *Session) {
s.writeMessage(m)
s.Close()
})
h.sessions.clear()
break loop
}
}
}
func (h *hub) closed() bool {
return !h.open.Load()
}
func (h *hub) len() int {
return h.sessions.len()
}
func (h *hub) all() []*Session {
return h.sessions.all()
}