-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebsocket-client.go
81 lines (66 loc) · 1.72 KB
/
websocket-client.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
package main
import (
"fmt"
"log"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
)
var (
wsUpgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
// #TODO
/*
const (
// Time allowed to write the file to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
*/
type WebSocketLink struct {
conn *websocket.Conn
wsMutex sync.Mutex
}
// Ensure you:
//
// defer sender.Close()
func NewWebSocketLink(host string, port int, path string) (*WebSocketLink, error) {
u := url.URL{
Scheme: "ws",
Host: fmt.Sprintf("%s:%d", host, port),
Path: path,
}
log.Printf("-> Connecting to %s", u.String())
s := WebSocketLink{}
var err error
s.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
return nil, err
}
return &s, nil
}
func (s *WebSocketLink) Close() error {
msg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
err := s.sendControlSignal(websocket.CloseMessage, msg, time.Second)
if err != nil {
// #TODO: log - though I don't know if we should still try close?
}
return s.conn.Close()
}
func (s *WebSocketLink) sendControlSignal(messageType int, data []byte, byDuration time.Duration) error {
s.wsMutex.Lock()
defer s.wsMutex.Unlock()
return s.conn.WriteControl(websocket.CloseMessage, data, time.Now().Add(byDuration))
}
func (s *WebSocketLink) sendData(data interface{}) error {
s.wsMutex.Lock()
defer s.wsMutex.Unlock()
return s.conn.WriteJSON(data)
}