/
hub.go
48 lines (43 loc) · 945 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
package main
import (
"time"
)
const (
readInterval = time.Second
)
type Hub struct {
connections map[*Connection]bool
broadcast chan []byte
register chan *Connection
unregister chan *Connection
}
var h = Hub{
broadcast: make(chan []byte),
register: make(chan *Connection),
unregister: make(chan *Connection),
connections: make(map[*Connection]bool),
}
func (h *Hub) run() {
for {
select {
case c := <-h.register:
h.connections[c] = true
dLogger.Println("Registered connection from %s", c.fromAddr)
monitor.SendInitMessages(c)
case c := <-h.unregister:
delete(h.connections, c)
close(c.send)
dLogger.Println("Unregistered connection from %s", c.fromAddr)
case m := <-h.broadcast:
for c := range h.connections {
dLogger.Println("Sending", string(m), "to", c.fromAddr)
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
}
}
}
}
}