-
Notifications
You must be signed in to change notification settings - Fork 22
/
hub.go
70 lines (61 loc) · 1.17 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
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
type Hub struct {
Clients map[*Client]bool
Broadcast chan []byte
Register chan *Client
Unregister chan *Client
}
func NewHub() *Hub {
return &Hub{
Clients: make(map[*Client]bool),
Broadcast: make(chan []byte),
Register: make(chan *Client),
Unregister: make(chan *Client),
}
}
func (h *Hub) 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 {
select {
case client.Send <- message:
default:
close(client.Send)
delete(h.Clients, client)
}
}
}
}
}
func (h *Hub) SocketHandler(w http.ResponseWriter, r *http.Request) {
u := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := u.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{
Hub: h,
Conn: conn,
Send: make(chan []byte, 256),
}
client.Hub.Register <- client
go client.WritePump()
go client.ReadPump()
}