-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
74 lines (66 loc) · 1.54 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
65
66
67
68
69
70
71
72
73
74
package main
type message struct {
data []byte
room string
}
type subscription struct {
conn *Client
room string
}
// hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
rooms map[string]map[*Client]bool
// Inbound messages from the clients.
broadcast chan message
// Register requests from the clients.
register chan subscription
// Unregister requests from clients.
unregister chan subscription
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan message),
register: make(chan subscription),
unregister: make(chan subscription),
rooms: make(map[string]map[*Client]bool),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
connections := h.rooms[client.room]
if connections == nil {
connections = make(map[*Client]bool)
h.rooms[client.room] = connections
}
h.rooms[client.room][client.conn] = true
case client := <-h.unregister:
connections := h.rooms[client.room]
if connections != nil {
if _, ok := connections[client.conn]; ok {
delete(connections, client.conn)
close(client.conn.send)
if len(connections) == 0 {
delete(h.rooms, client.room)
}
}
}
case message := <-h.broadcast:
connections := h.rooms[message.room]
for client := range connections {
select {
case client.send <- message.data:
default:
close(client.send)
delete(connections, client)
if len(connections) == 0 {
delete(h.rooms, message.room)
}
}
}
}
}
}