-
Notifications
You must be signed in to change notification settings - Fork 3
/
wsmanager.go
80 lines (67 loc) · 1.55 KB
/
wsmanager.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
package websocket
import (
"flag"
"fmt"
"net/url"
"github.com/gorilla/websocket"
)
const addr string = "api.exchange.cryptomkt.com"
// wsManager deals with the server communication, it sends and recieves data
// the way to use it is to snd via its send channel and to recieve in a loop
// via its rcv channel. creation and connection are separated. closable
type wsManager struct {
streamPath string
conn *websocket.Conn
snd chan []byte
rcv chan []byte
isOpen bool
}
func newWSManager(path string) *wsManager {
return &wsManager{
streamPath: path,
snd: make(chan []byte, 1),
rcv: make(chan []byte, 1),
isOpen: false,
}
}
func (ws *wsManager) connect() error {
flag.Parse()
u := url.URL{Scheme: "wss", Host: addr, Path: ws.streamPath}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
return fmt.Errorf("dial: %v", err)
}
ws.conn = c
go ws.rcvLoop()
go ws.sndLoop()
ws.isOpen = true
return nil
}
func (ws *wsManager) close() {
ws.isOpen = false
close(ws.snd)
}
func (ws *wsManager) sndLoop() {
for msg := range ws.snd {
err := ws.conn.WriteMessage(websocket.TextMessage, msg)
if err != nil {
return
}
}
// send close msg to server
err := ws.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
return
}
}
func (ws *wsManager) rcvLoop() {
defer close(ws.rcv)
for {
_, message, err := ws.conn.ReadMessage()
if err != nil {
ws.conn.Close()
return
}
ws.rcv <- message
}
}