forked from StevenWeathers/thunderdome-planning-poker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
73 lines (65 loc) · 1.5 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
package main
type message struct {
data []byte
arena string
}
type subscription struct {
conn *connection
arena string
warriorID string
}
// hub maintains the set of active connections and broadcasts messages to the
// connections.
type hub struct {
// Registered connections.
arenas map[string]map[*connection]bool
// Inbound messages from the connections.
broadcast chan message
// Register requests from the connections.
register chan subscription
// Unregister requests from connections.
unregister chan subscription
}
var h = hub{
broadcast: make(chan message),
register: make(chan subscription),
unregister: make(chan subscription),
arenas: make(map[string]map[*connection]bool),
}
func (h *hub) run() {
for {
select {
case s := <-h.register:
connections := h.arenas[s.arena]
if connections == nil {
connections = make(map[*connection]bool)
h.arenas[s.arena] = connections
}
h.arenas[s.arena][s.conn] = true
case s := <-h.unregister:
connections := h.arenas[s.arena]
if connections != nil {
if _, ok := connections[s.conn]; ok {
delete(connections, s.conn)
close(s.conn.send)
if len(connections) == 0 {
delete(h.arenas, s.arena)
}
}
}
case m := <-h.broadcast:
connections := h.arenas[m.arena]
for c := range connections {
select {
case c.send <- m.data:
default:
close(c.send)
delete(connections, c)
if len(connections) == 0 {
delete(h.arenas, m.arena)
}
}
}
}
}
}