-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathhub.go
More file actions
79 lines (63 loc) · 1.17 KB
/
hub.go
File metadata and controls
79 lines (63 loc) · 1.17 KB
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
package melody
import (
"sync"
"sync/atomic"
)
type hub struct {
mu sync.RWMutex
sessions map[*Session]struct{}
open atomic.Bool
}
func newHub() *hub {
hub := &hub{
sessions: make(map[*Session]struct{}),
}
hub.open.Store(true)
return hub
}
func (h *hub) closed() bool {
return !h.open.Load()
}
func (h *hub) len() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.sessions)
}
func (h *hub) all() []*Session {
h.mu.RLock()
defer h.mu.RUnlock()
result := make([]*Session, 0, len(h.sessions))
for s := range h.sessions {
result = append(result, s)
}
return result
}
func (h *hub) register(s *Session) {
h.mu.Lock()
defer h.mu.Unlock()
h.sessions[s] = struct{}{}
}
func (h *hub) unregister(s *Session) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.sessions, s)
}
func (h *hub) exit(msg envelope) {
h.mu.Lock()
defer h.mu.Unlock()
for s := range h.sessions {
s.writeMessage(msg)
s.Close()
}
h.sessions = make(map[*Session]struct{})
h.open.Store(false)
}
func (h *hub) broadcast(msg envelope) {
h.mu.RLock()
defer h.mu.RUnlock()
for s := range h.sessions {
if msg.filter == nil || msg.filter(s) {
s.writeMessage(msg)
}
}
}