-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
66 lines (53 loc) · 988 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
55
56
57
58
59
60
61
62
63
64
65
66
package main
// import "log"
type hub struct {
// Registered clients
clients map[*client]bool
// Inbound messages
broadcast chan string
// Register requests
register chan *client
// Unregister requests
unregister chan *client
content string
}
var h = hub{
broadcast: make(chan string),
register: make(chan *client),
unregister: make(chan *client),
clients: make(map[*client]bool),
content: "",
}
func (h *hub) run() {
for { //forever
select {
case c := <-h.register:
h.clients[c] = true
c.send <- []byte(h.content)
break
case c := <-h.unregister:
_, ok := h.clients[c]
if ok {
delete(h.clients, c)
close(c.send)
}
break
case m := <-h.broadcast:
h.content = m
h.broadcastMessage()
break
}
}
}
func (h *hub) broadcastMessage() {
for c := range h.clients {
select {
case c.send <- []byte(h.content):
break
// We can't reach the client
default:
close(c.send)
delete(h.clients, c)
}
}
}