-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_hub.go
More file actions
55 lines (45 loc) · 977 Bytes
/
debug_hub.go
File metadata and controls
55 lines (45 loc) · 977 Bytes
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
//go:build forge_debug
package forge
import (
"net"
"sync"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
// debugHub manages active WebSocket client connections and broadcasts messages.
type debugHub struct {
mu sync.Mutex
clients map[net.Conn]struct{}
}
func newDebugHub() *debugHub {
return &debugHub{clients: make(map[net.Conn]struct{})}
}
func (h *debugHub) add(conn net.Conn) {
h.mu.Lock()
h.clients[conn] = struct{}{}
h.mu.Unlock()
}
func (h *debugHub) remove(conn net.Conn) {
h.mu.Lock()
delete(h.clients, conn)
h.mu.Unlock()
conn.Close()
}
func (h *debugHub) broadcast(data []byte) {
h.mu.Lock()
conns := make([]net.Conn, 0, len(h.clients))
for c := range h.clients {
conns = append(conns, c)
}
h.mu.Unlock()
for _, c := range conns {
if err := wsutil.WriteServerMessage(c, ws.OpText, data); err != nil {
h.remove(c)
}
}
}
func (h *debugHub) count() int {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.clients)
}