forked from binance/binance-connector-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
125 lines (110 loc) · 2.56 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package binance_connector
import (
"fmt"
"net/http"
"time"
"github.com/gorilla/websocket"
)
// WsHandler handle raw websocket message
type WsHandler func(message []byte)
// ErrHandler handles errors
type ErrHandler func(err error)
// WsConfig webservice configuration
type WsConfig struct {
Endpoint string
}
type WebsocketStreamClient struct {
Endpoint string
IsCombined bool
}
func NewWebsocketStreamClient(isCombined bool, baseURL ...string) *WebsocketStreamClient {
// Set default base URL to production WS URL
url := "wss://stream.binance.com:9443"
if len(baseURL) > 0 {
url = baseURL[0]
}
// Append to baseURL based on whether the client is for combined streams or not
if isCombined {
url += "/stream?streams="
} else {
url += "/ws"
}
return &WebsocketStreamClient{
Endpoint: url,
IsCombined: isCombined,
}
}
func newWsConfig(endpoint string) *WsConfig {
return &WsConfig{
Endpoint: endpoint,
}
}
var wsServe = func(cfg *WsConfig, handler WsHandler, errHandler ErrHandler) (doneCh, stopCh chan struct{}, err error) {
Dialer := websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
EnableCompression: false,
}
headers := http.Header{}
headers.Add("User-Agent", fmt.Sprintf("%s/%s", Name, Version))
c, _, err := Dialer.Dial(cfg.Endpoint, headers)
if err != nil {
return nil, nil, err
}
c.SetReadLimit(655350)
doneCh = make(chan struct{})
stopCh = make(chan struct{})
go func() {
// This function will exit either on error from
// websocket.Conn.ReadMessage or when the stopC channel is
// closed by the client.
defer close(doneCh)
if WebsocketKeepalive {
keepAlive(c, WebsocketTimeout)
}
// Wait for the stopC channel to be closed. We do that in a
// separate goroutine because ReadMessage is a blocking
// operation.
silent := false
go func() {
select {
case <-stopCh:
silent = true
case <-doneCh:
}
}()
for {
_, message, err := c.ReadMessage()
if err != nil {
if !silent {
errHandler(err)
}
return
}
handler(message)
}
}()
return
}
func keepAlive(c *websocket.Conn, timeout time.Duration) {
ticker := time.NewTicker(timeout)
lastResponse := time.Now()
c.SetPongHandler(func(msg string) error {
lastResponse = time.Now()
return nil
})
go func() {
defer ticker.Stop()
for {
deadline := time.Now().Add(10 * time.Second)
err := c.WriteControl(websocket.PingMessage, []byte{}, deadline)
if err != nil {
return
}
<-ticker.C
if time.Since(lastResponse) > timeout {
return
}
}
}()
}