-
Notifications
You must be signed in to change notification settings - Fork 4
/
hub.go
54 lines (44 loc) · 758 Bytes
/
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
package main
import (
"log"
"sync"
)
type hub struct {
mu sync.Mutex
clients []*client
}
func (b *hub) sub(c *client) {
b.mu.Lock()
defer b.mu.Unlock()
b.clients = append(b.clients, c)
}
func (b *hub) usub(c *client) {
b.mu.Lock()
defer b.mu.Unlock()
n := b.clients[:0]
for _, x := range b.clients {
if x != c {
n = append(n, x)
}
}
b.clients = n
}
func (b *hub) pub(v interface{}) {
b.mu.Lock()
defer b.mu.Unlock()
for _, c := range b.clients {
// send but do not block for it
select {
case c.c <- v:
default:
log.Printf("failed to broadcast %v to %v as the receiving channel is busy\n", v, c)
}
}
}
func (b *hub) stop() {
b.mu.Lock()
defer b.mu.Unlock()
for _, c := range b.clients {
c.close()
}
}