-
Notifications
You must be signed in to change notification settings - Fork 1
/
hub.go
51 lines (45 loc) · 1.1 KB
/
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
package main
// hub is a struct who contain all current clients and all communications channels
type hub struct {
// Registered clients.
clients map[*client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *client
// Unregister requests from clients.
unregister chan *client
}
// Get new clean hub
func newHub() *hub {
return &hub{
clients: make(map[*client]bool),
broadcast: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
}
}
// Add / Del client from hub with channel and broadcast to all people with channel too
func (h *hub) run() {
for {
// Wait for the channels to receive a message
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}