-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhub.go
49 lines (42 loc) · 980 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
package main
import (
"log"
)
type hub struct {
// Register response to the connections.
respond chan *response
// Register requests from the connections.
register chan *connection
// Unregister requests from connections.
unregister chan *connection
// Registered connections.
connections map[*connection]bool
}
var h = hub{
respond: make(chan *response),
register: make(chan *connection),
unregister: make(chan *connection),
connections: make(map[*connection]bool),
}
func (h *hub) run() {
for {
select {
case conn := <-h.register:
log.Printf("Connection registered")
h.connections[conn] = true
case conn := <-h.unregister:
log.Printf("Connection unregistered")
delete(h.connections, conn)
close(conn.send)
case response := <-h.respond:
conn := response.conn
select {
case conn.send <- response.value:
default:
delete(h.connections, conn)
close(conn.send)
go conn.ws.Close()
}
}
}
}