/
wshub.go
62 lines (54 loc) 路 1.27 KB
/
wshub.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
package web
import (
"fmt"
"net/http"
"os"
)
// WsHub maintains the set of active clients and broadcasts messages to the clients.
type WsHub struct {
// Inbound messages from the clients.
Broadcast chan []byte
// Register requests from the clients.
Register chan *WsClient
// Unregister requests from clients.
Unregister chan *WsClient
// Registered clients.
clients map[*WsClient]bool
}
// NewHub creates new WsHub
func NewHub() *WsHub {
return &WsHub{
Broadcast: make(chan []byte),
Register: make(chan *WsClient),
Unregister: make(chan *WsClient),
clients: make(map[*WsClient]bool),
}
}
// Run handles communication operations with WsHub
func (h *WsHub) Run() {
for {
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 {
client.send <- message
}
}
}
}
func (h *WsHub) handler(w http.ResponseWriter, r *http.Request) {
wsClient, err := NewWsClient(h, w, r)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create WebSocket client: %v", err)
return
}
h.Register <- wsClient
go wsClient.HandleReads()
go wsClient.HandleWrites()
}