-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconn_hub.go
46 lines (43 loc) · 1.03 KB
/
conn_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
package main
type ConnHub struct {
clients map[*Client]string
broadcast chan []byte
register chan *Client
unregister chan *Client
}
// init ConnHub
func newConnHub() *ConnHub {
return &ConnHub{
clients: make(map[*Client]string),
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
}
}
// handles channel actions of a ConnHub
func (hub *ConnHub) run() {
for {
select {
// register client to hub
case client := <-hub.register:
hub.clients[client] = client.name
// unregister client to hub
case client := <-hub.unregister:
if _, ok := hub.clients[client]; ok {
delete(hub.clients, client)
close(client.send)
}
// loop through registered clients and send message to their send channel
case message := <-hub.broadcast:
for client := range hub.clients {
select {
case client.send <- message:
// if send buffer is full, assume client is dead or stuck and unregister
default:
close(client.send)
delete(hub.clients, client)
}
}
}
}
}