-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.go
More file actions
143 lines (127 loc) · 3.4 KB
/
websocket.go
File metadata and controls
143 lines (127 loc) · 3.4 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package main
import (
"context"
"log/slog"
"sync"
"github.com/coder/websocket"
)
type WSMessage string
type Client struct {
conn *websocket.Conn
send chan WSMessage
hub *WebSocketHub
studentID int64
}
type WebSocketHub struct {
clients map[int64]map[*Client]struct{}
broadcast chan WSMessage
register chan *Client
unregister chan *Client
mu sync.RWMutex
broadcastTarget chan struct {
studentIDs []int64
message WSMessage
}
}
func NewWebSocketHub() *WebSocketHub {
return &WebSocketHub{
clients: make(map[int64]map[*Client]struct{}),
broadcast: make(chan WSMessage, 256),
register: make(chan *Client),
unregister: make(chan *Client),
broadcastTarget: make(chan struct {
studentIDs []int64
message WSMessage
}, 256),
}
}
func (h *WebSocketHub) Run() {
for {
select {
case client := <-h.register:
h.mu.Lock()
if _, ok := h.clients[client.studentID]; !ok {
h.clients[client.studentID] = make(map[*Client]struct{})
}
h.clients[client.studentID][client] = struct{}{}
h.mu.Unlock()
slog.Info(logMsgWebsocketClientRegistered, slog.Int64("student_id", client.studentID))
case client := <-h.unregister:
h.mu.Lock()
if clients, ok := h.clients[client.studentID]; ok {
if _, exists := clients[client]; exists {
delete(clients, client)
close(client.send)
if len(clients) == 0 {
delete(h.clients, client.studentID)
}
}
}
h.mu.Unlock()
slog.Info(logMsgWebsocketClientUnregistered, slog.Int64("student_id", client.studentID))
case message := <-h.broadcast:
h.mu.RLock()
for _, clients := range h.clients {
for client := range clients {
select {
case client.send <- message:
default:
slog.Warn(logMsgWebsocketDropSlowClient)
}
}
}
h.mu.RUnlock()
slog.Info(logMsgWebsocketBroadcastAll, slog.String("message", string(message)))
case target := <-h.broadcastTarget:
h.mu.RLock()
for _, studentID := range target.studentIDs {
if clients, ok := h.clients[studentID]; ok {
for client := range clients {
select {
case client.send <- target.message:
default:
slog.Warn(logMsgWebsocketDropTargetedSlowClient)
}
}
}
}
h.mu.RUnlock()
slog.Info(logMsgWebsocketBroadcastTargeted, slog.String("message", string(target.message)), slog.Int("targets", len(target.studentIDs)))
}
}
}
func (h *WebSocketHub) Broadcast(msg WSMessage) {
h.broadcast <- msg
}
func (h *WebSocketHub) BroadcastToStudents(studentIDs []int64, msg WSMessage) {
h.broadcastTarget <- struct {
studentIDs []int64
message WSMessage
}{studentIDs: studentIDs, message: msg}
}
func (c *Client) writePump() {
defer func() {
_ = c.conn.Close(websocket.StatusNormalClosure, "")
}()
for message := range c.send {
if err := c.conn.Write(context.Background(), websocket.MessageText, []byte(message)); err != nil {
slog.Error(logMsgWebsocketWriteError, slog.Any("error", err))
return
}
}
}
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
_ = c.conn.Close(websocket.StatusNormalClosure, "")
}()
for {
_, _, err := c.conn.Read(context.Background())
if err != nil {
if websocket.CloseStatus(err) != websocket.StatusNormalClosure && websocket.CloseStatus(err) != websocket.StatusGoingAway {
slog.Error(logMsgWebsocketReadError, slog.Any("error", err))
}
break
}
}
}