-
Notifications
You must be signed in to change notification settings - Fork 0
/
hubs.go
50 lines (43 loc) · 860 Bytes
/
hubs.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
package ws
import (
"fmt"
"sync"
)
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered users.
users map[*User]bool
// Register requests from the actuators.
register chan *User
// Unregister requests from actuators.
unregister chan *User
}
var once sync.Once
var hub *Hub
func NewHub() *Hub {
once.Do(func() {
hub = &Hub{
users: make(map[*User]bool),
register: make(chan *User),
unregister: make(chan *User),
}
})
go hub.run()
return hub
}
func (hub *Hub) run() {
for {
select {
case client := <-hub.register:
fmt.Println("register", client)
hub.users[client] = true
case client := <-hub.unregister:
fmt.Println("unregister", client)
if _, ok := hub.users[client]; ok {
delete(hub.users, client)
close(client.send)
}
}
}
}