-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ws.go
89 lines (78 loc) · 1.75 KB
/
ws.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
package hub
import (
"encoding/json"
"fmt"
"html/template"
"net"
"time"
"golang.org/x/net/websocket"
)
type wsLink struct {
conn *websocket.Conn
lastRecv time.Time
lastSend time.Time
}
type announcement struct {
Id string
Model string
Name string
DeployParams template.HTML
}
func (l *wsLink) Send(pkt *Packet) error {
data, err := json.Marshal(pkt)
if err != nil {
return fmt.Errorf("Marshal error: %w", err)
}
if err := websocket.Message.Send(l.conn, string(data)); err != nil {
return fmt.Errorf("Send error: %w", err)
}
l.lastSend = time.Now()
return nil
}
func (l *wsLink) Close() {
l.conn.Close()
}
func (l *wsLink) receive() (*Packet, error) {
var data []byte
var pkt Packet
if err := websocket.Message.Receive(l.conn, &data); err != nil {
return nil, err
}
l.lastRecv = time.Now()
if err := json.Unmarshal(data, &pkt); err != nil {
return nil, fmt.Errorf("Unmarshalling error: %w", err)
}
return &pkt, nil
}
func (l *wsLink) receiveTimeout(timeout time.Duration) (*Packet, error) {
l.conn.SetReadDeadline(time.Now().Add(timeout))
pkt, err := l.receive()
l.conn.SetReadDeadline(time.Time{})
return pkt, err
}
var pingDuration = 4 * time.Second
var pingTimeout = 2*pingDuration + time.Second
func (l *wsLink) receivePoll() (*Packet, error) {
for {
if time.Since(l.lastSend) >= pingDuration {
if err := l.Send(&Packet{Path: "/ping"}); err != nil {
return nil, err
}
}
pkt, err := l.receiveTimeout(time.Second)
if err == nil {
if pkt.Path == "/ping" {
continue
}
return pkt, nil
}
if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
if time.Since(l.lastRecv) > pingTimeout {
return nil, err
}
continue
}
return nil, err
}
return nil, nil
}