This repository has been archived by the owner on Apr 17, 2024. It is now read-only.
/
hub.go
90 lines (78 loc) · 1.88 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package asteroid
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
log "unknwon.dev/clog/v2"
)
// Hub contains all the connections and the action signal.
type Hub struct {
// Registered clients.
clients map[*client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *client
// Unregister requests from clients.
unregister chan *client
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
clients: make(map[*client]bool),
}
}
// ServeWebSocket handles websocket requests from the peer.
func ServeWebSocket(c *gin.Context) {
hub.serve(c)
}
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) serve(c *gin.Context) {
// Upgrade the request to websocket.
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Ignore origin checking.
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Error("Failed to upgrade: %v", err)
return
}
client := &client{hub: h, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
}
func (h *Hub) sendMessage(messageType string, data interface{}) {
jsonData, _ := json.Marshal(&unityData{
Type: messageType,
Data: data,
})
h.broadcast <- jsonData
}