-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
64 lines (57 loc) · 1.45 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
52
53
54
55
56
57
58
59
60
61
62
63
64
package gws
import (
"log"
)
type Hub struct {
clients map[string]*client
fromClient chan Message
toClient chan Message
broadcast chan []byte
register chan *client
unregister chan *client
}
func newHub() *Hub {
return &Hub{
fromClient: make(chan Message),
toClient: make(chan Message),
broadcast: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
clients: make(map[string]*client),
}
}
func (h *Hub) closeConnection(clientId string) {
close(h.clients[clientId].send)
delete(h.clients, clientId)
log.Printf("Closing connection to client %v\n", clientId)
}
func (h *Hub) run(outbound chan Message) {
for {
select {
case client := <-h.register:
h.clients[client.id] = client
outbound <- *(newMessage(client.id, ClientConnected, []byte{}))
case client := <-h.unregister:
if _, ok := h.clients[client.id]; ok {
h.closeConnection(client.id)
outbound <- *(newMessage(client.id, ClientDisconnected, []byte{}))
}
case message := <-h.fromClient:
outbound <- message
case message := <-h.toClient:
select {
case h.clients[message.ClientId].send <- message.Data:
default:
h.closeConnection(message.ClientId)
}
case broadcast := <-h.broadcast:
for clientId := range h.clients {
select {
case h.clients[clientId].send <- broadcast:
default:
h.closeConnection(clientId)
}
}
}
}
}