forked from calaos/calaos-homekit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
92 lines (72 loc) · 1.48 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
package main
import (
"errors"
"time"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
var ErrNotConnected = errors.New("websocket is not connected")
type WebSocketClient struct {
isConnected bool
url string
conn *websocket.Conn
connectedCb func()
}
func (ws *WebSocketClient) closeAndRecconect() {
ws.Close()
go func() {
ws.connect()
}()
}
func (ws *WebSocketClient) Close() {
if ws.conn != nil {
ws.conn.Close()
}
ws.isConnected = false
}
func Dial(url string, connectedCb func()) *WebSocketClient {
ws := &WebSocketClient{
url: url,
connectedCb: connectedCb,
}
go func() {
ws.connect()
}()
return ws
}
func (ws *WebSocketClient) connect() {
for {
var err error
ws.conn, _, err = websocket.DefaultDialer.Dial(ws.url, nil)
if err == nil {
ws.isConnected = true
ws.connectedCb()
break
}
log.Error("dial:", err)
time.Sleep(10 * time.Second)
}
}
func (ws *WebSocketClient) WriteMessage(messageType int, data []byte) error {
err := ErrNotConnected
if ws.IsConnected() {
err = ws.conn.WriteMessage(messageType, data)
if err != nil {
ws.closeAndRecconect()
}
}
return err
}
func (ws *WebSocketClient) ReadMessage() (messageType int, message []byte, err error) {
err = ErrNotConnected
if ws.IsConnected() {
messageType, message, err = ws.conn.ReadMessage()
if err != nil {
ws.closeAndRecconect()
}
}
return
}
func (ws *WebSocketClient) IsConnected() bool {
return ws.isConnected
}