-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
85 lines (70 loc) · 1.99 KB
/
Copy pathclient.go
File metadata and controls
85 lines (70 loc) · 1.99 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
package websocket
import (
"encoding/json"
"sync"
"time"
"github.com/HyperloopUPV-H8/h9-backend/pkg/abstraction"
ws "github.com/gorilla/websocket"
)
// HeartbeatTopic is the liveness message every frontend sends once per
// second. It is consumed by the websocket layer and never reaches the broker.
const HeartbeatTopic = "connection/heartbeat"
// heartbeatTimeout bounds how long a dead or frozen frontend goes undetected:
// if no message (the heartbeat guarantees one per second) arrives within this
// window, Read fails and the client is treated as disconnected.
const heartbeatTimeout = 3 * time.Second
type Client struct {
readMx *sync.Mutex
writeMx *sync.Mutex
conn *ws.Conn
onCloseMx *sync.Mutex
onClose func()
}
func NewClient(conn *ws.Conn) *Client {
client := &Client{
readMx: &sync.Mutex{},
writeMx: &sync.Mutex{},
conn: conn,
onCloseMx: &sync.Mutex{},
onClose: func() {},
}
conn.SetReadDeadline(time.Now().Add(heartbeatTimeout))
return client
}
func (client *Client) SetOnClose(onClose func()) {
client.onCloseMx.Lock()
defer client.onCloseMx.Unlock()
client.onClose = onClose
}
type Message struct {
Topic abstraction.BrokerTopic `json:"topic"`
Payload json.RawMessage `json:"payload"`
}
func (client *Client) Read() (Message, error) {
client.readMx.Lock()
defer client.readMx.Unlock()
var message Message
err := client.conn.ReadJSON(&message)
if err == nil {
client.conn.SetReadDeadline(time.Now().Add(heartbeatTimeout))
}
return message, err
}
func (client *Client) Write(message Message) error {
client.writeMx.Lock()
defer client.writeMx.Unlock()
return client.conn.WriteJSON(message)
}
func (client *Client) Close(code int, reason string) error {
client.writeMx.Lock()
defer client.writeMx.Unlock()
client.conn.WriteControl(
ws.CloseMessage,
ws.FormatCloseMessage(code, reason),
time.Now().Add(time.Second),
)
client.onCloseMx.Lock()
defer client.onCloseMx.Unlock()
client.onClose()
return client.conn.Close()
}