-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
96 lines (74 loc) · 1.9 KB
/
websocket.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
91
92
93
94
95
96
package main
import (
"net"
"net/http"
"sync"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/google/uuid"
)
var wsOnce sync.Once
var wsRwm sync.RWMutex
// WebsocketServer struct
type WebsocketServer struct {
connections map[[16]byte]*net.Conn
}
var websocketInstance *WebsocketServer
// AddConnection adds new conection from http handler
func (server WebsocketServer) AddConnection(w http.ResponseWriter, r *http.Request, f func([]byte)) ([16]byte, error) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
var idConnection [16]byte
if err != nil {
return idConnection, err
}
wsRwm.Lock()
defer wsRwm.Unlock()
idConnection = uuid.New()
websocketInstance.connections[idConnection] = &conn
go func() {
for {
msg, _, err := wsutil.ReadClientData(conn)
if err == nil {
f(msg)
} else {
wsRwm.Lock()
defer wsRwm.Unlock()
delete(websocketInstance.connections, idConnection)
return
}
}
}()
return idConnection, nil
}
// InitWebsocketServer initialize the websocket server
func InitWebsocketServer() error {
if websocketInstance == nil {
wsOnce.Do(func() {
websocketInstance = &WebsocketServer{
connections: make(map[[16]byte]*net.Conn),
}
})
}
return nil
}
// GetWebsocketServerInstance returns websocket server instance
func GetWebsocketServerInstance() *WebsocketServer {
return websocketInstance
}
// BroadcastMessage broadcast message to all connections
func (server WebsocketServer) BroadcastMessage(body []byte) {
wsRwm.Lock()
defer wsRwm.Unlock()
for _, v := range server.connections {
wsutil.WriteServerMessage(*v, ws.OpText, body)
}
}
// SendMessage send message to individual connection
func (server WebsocketServer) SendMessage(body []byte, idConnection [16]byte) {
wsRwm.Lock()
defer wsRwm.Unlock()
connection, exists := server.connections[idConnection]
if exists {
wsutil.WriteServerMessage(*connection, ws.OpText, body)
}
}