-
Notifications
You must be signed in to change notification settings - Fork 6
/
ws_client.go
115 lines (96 loc) · 1.99 KB
/
ws_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
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
package transport
import (
"bytes"
"time"
"github.com/msw-x/moon/app"
"github.com/msw-x/moon/ulog"
)
type WsClient struct {
ws *WsConn
heartbeatTimeout time.Duration
onMessage func(string, []byte)
}
func NewWsClient(url string) *WsClient {
return &WsClient{
ws: NewWsConn(url),
heartbeatTimeout: time.Second * 20,
}
}
func (o *WsClient) Shutdown() {
o.ws.Shutdown()
}
func (o *WsClient) WithUrl(url string) *WsClient {
o.ws.WithUrl(url)
return o
}
func (o *WsClient) WithByTickUrl() *WsClient {
o.ws.WithByTickUrl()
return o
}
func (o *WsClient) WithLog(log *ulog.Log) *WsClient {
o.ws.WithLog(log)
return o
}
func (o *WsClient) Conf() *WsConf {
return o.ws.Conf()
}
func (o *WsClient) WithProxy(proxy string) *WsClient {
o.Conf().SetProxy(proxy)
return o
}
func (o *WsClient) Connected() bool {
return o.ws.Connected()
}
func (o *WsClient) Run() {
o.ws.SetOnMessage(o.processMessage)
o.ws.Run()
app.Go(func() {
for o.ws.Do() {
o.ws.Sleep(o.heartbeatTimeout)
if !o.ws.Do() {
break
}
if !o.ws.Connected() {
continue
}
o.ping()
}
})
}
func (o *WsClient) SetOnMessage(onMessage func(string, []byte)) {
o.onMessage = onMessage
}
func (o *WsClient) SetOnConnected(onConnected func()) {
o.ws.SetOnConnected(onConnected)
}
func (o *WsClient) SetOnDisconnected(onDisconnected func()) {
o.ws.SetOnDisconnected(onDisconnected)
}
func (o *WsClient) SetOnDialError(onDialError func(error) bool) {
o.ws.SetOnDialError(onDialError)
}
func (o *WsClient) Send(cmd any) bool {
return o.ws.Send(cmd)
}
func (o *WsClient) ping() bool {
return o.ws.Send(struct {
Cmd string `json:"op"`
}{
Cmd: "ping",
})
}
func (o *WsClient) processMessage(msg []byte) {
prefix := []byte(`{"`)
if bytes.HasPrefix(msg, prefix) {
m := bytes.TrimPrefix(msg, prefix)
i := bytes.IndexByte(m, '"')
if i > -1 {
name := string(m[:i])
if o.onMessage != nil {
o.onMessage(name, msg)
}
return
}
}
panic("message type not detected")
}