-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathclient.go
More file actions
387 lines (343 loc) · 8.7 KB
/
client.go
File metadata and controls
387 lines (343 loc) · 8.7 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package gotdx
import (
"bytes"
"compress/zlib"
"encoding/binary"
"errors"
"io"
"log"
"net"
"sync"
"time"
"github.com/bensema/gotdx/proto"
)
type clientMode uint8
const (
clientModeMain clientMode = iota
clientModeEx
clientModeMacMain
clientModeMacEx
)
func New(opts ...Option) *Client {
return newClientWithOptions(applyOptions(opts...), clientModeMain)
}
func NewEx(opts ...Option) *Client {
return newClientWithOptions(applyOptions(opts...), clientModeEx)
}
func NewMAC(opts ...Option) *Client {
return newClientWithOptions(applyOptions(opts...), clientModeMacMain)
}
func NewMACEx(opts ...Option) *Client {
return newClientWithOptions(applyOptions(opts...), clientModeMacEx)
}
type Client struct {
conn net.Conn
opt *Options
complete chan bool
sending chan bool
mu sync.Mutex
mode clientMode
main *Client
ex *Client
}
func (client *Client) CurrentAddress() string {
if client == nil || client.opt == nil {
return ""
}
return client.opt.TCPAddress
}
// ProbeHosts probes the client's configured address list and returns the
// results sorted by reachability and latency.
func (client *Client) ProbeHosts() []HostProbeResult {
if client == nil || client.opt == nil {
return nil
}
return ProbeAddresses(client.addresses(), client.timeout())
}
// FastestHost returns the fastest reachable configured address.
func (client *Client) FastestHost() (HostProbeResult, error) {
if client == nil || client.opt == nil {
return HostProbeResult{}, ErrNoReachableHosts
}
return FastestAddress(client.addresses(), client.timeout())
}
func newClientWithOptions(opt *Options, mode clientMode) *Client {
client := &Client{
opt: cloneOptions(opt),
sending: make(chan bool, 1),
complete: make(chan bool, 1),
mode: mode,
}
if mode == clientModeEx {
client.opt.TCPAddress = client.opt.ExTCPAddress
client.opt.TCPAddressPool = append([]string(nil), client.opt.ExTCPAddressPool...)
}
if mode == clientModeMacMain {
client.opt.TCPAddress = client.opt.MacTCPAddress
client.opt.TCPAddressPool = append([]string(nil), client.opt.MacTCPAddressPool...)
}
if mode == clientModeMacEx {
client.opt.TCPAddress = client.opt.MacExTCPAddress
client.opt.TCPAddressPool = append([]string(nil), client.opt.MacExTCPAddressPool...)
}
return client
}
func cloneOptions(opt *Options) *Options {
if opt == nil {
return defaultOptions()
}
clone := *opt
clone.TCPAddressPool = append([]string(nil), opt.TCPAddressPool...)
clone.ExTCPAddressPool = append([]string(nil), opt.ExTCPAddressPool...)
clone.MacTCPAddressPool = append([]string(nil), opt.MacTCPAddressPool...)
clone.MacExTCPAddressPool = append([]string(nil), opt.MacExTCPAddressPool...)
return &clone
}
func (client *Client) connect() error {
addresses := client.connectionOrder()
if len(addresses) == 0 {
return errors.New("no tcp address configured")
}
var lastErr error
for _, address := range addresses {
if err := client.connectToAddress(address); err != nil {
lastErr = err
continue
}
return nil
}
if lastErr == nil {
lastErr = errors.New("no available tcp address")
}
return lastErr
}
func (client *Client) connectToAddress(address string) error {
conn, err := net.DialTimeout("tcp", address, client.timeout())
if err != nil {
return err
}
client.conn = conn
client.opt.TCPAddress = address
return nil
}
func (client *Client) addresses() []string {
addresses := make([]string, 0, 1+len(client.opt.TCPAddressPool))
if client.opt.TCPAddress != "" {
addresses = append(addresses, client.opt.TCPAddress)
}
addresses = append(addresses, client.opt.TCPAddressPool...)
return addresses
}
func (client *Client) connectionOrder() []string {
if client == nil || client.opt == nil {
return nil
}
addresses := client.addresses()
if len(addresses) == 0 {
return nil
}
if !client.opt.AutoSelectFastest {
return addresses
}
results := ProbeAddresses(addresses, client.timeout())
if len(results) == 0 {
return addresses
}
ordered := make([]string, 0, len(addresses))
seen := make(map[string]struct{}, len(addresses))
for _, result := range results {
if !result.Reachable {
continue
}
if _, ok := seen[result.Address]; ok {
continue
}
ordered = append(ordered, result.Address)
seen[result.Address] = struct{}{}
}
for _, address := range addresses {
if _, ok := seen[address]; ok {
continue
}
ordered = append(ordered, address)
}
return ordered
}
func (client *Client) timeout() time.Duration {
if client == nil || client.opt == nil {
return time.Duration(_defaultTimeoutSec) * time.Second
}
timeout := time.Duration(client.opt.TimeoutSec) * time.Second
if timeout <= 0 {
return time.Duration(_defaultTimeoutSec) * time.Second
}
return timeout
}
func (client *Client) closeCurrentConn() {
if client.conn != nil {
_ = client.conn.Close()
client.conn = nil
}
}
func (client *Client) connectWithHandshake(handshake func() error) error {
addresses := client.connectionOrder()
if len(addresses) == 0 {
return errors.New("no tcp address configured")
}
var lastErr error
for _, address := range addresses {
if err := client.connectToAddress(address); err != nil {
lastErr = err
continue
}
if err := handshake(); err == nil {
return nil
} else {
lastErr = err
client.closeCurrentConn()
}
}
if lastErr == nil {
lastErr = errors.New("no available tcp address")
}
return lastErr
}
func (client *Client) exchange(builder proto.RequestBuilder) (*proto.RespHeader, []byte, error) {
if client.conn == nil {
return nil, nil, errors.New("connection is nil")
}
_ = client.conn.SetDeadline(time.Now().Add(client.timeout()))
defer func() {
_ = client.conn.SetDeadline(time.Time{})
}()
sendData, err := builder.BuildRequest()
if err != nil {
return nil, nil, err
}
retryTimes := 0
for {
n, err := client.conn.Write(sendData)
if n < len(sendData) {
retryTimes++
if retryTimes <= client.opt.MaxRetryTimes {
log.Printf("第%d次重试\n", retryTimes)
} else {
return nil, nil, err
}
} else {
if err != nil {
return nil, nil, err
}
break
}
}
headerBytes := make([]byte, proto.MessageHeaderBytes)
_, err = io.ReadFull(client.conn, headerBytes)
if err != nil {
return nil, nil, err
}
headerBuf := bytes.NewReader(headerBytes)
var header proto.RespHeader
if err := binary.Read(headerBuf, binary.LittleEndian, &header); err != nil {
return nil, nil, err
}
if header.ZipSize > proto.MessageMaxBytes {
log.Printf("msgData has bytes(%d) beyond max %d\n", header.ZipSize, proto.MessageMaxBytes)
return nil, nil, ErrBadData
}
msgData := make([]byte, header.ZipSize)
_, err = io.ReadFull(client.conn, msgData)
if err != nil {
return nil, nil, err
}
if header.ZipSize != header.UnZipSize {
var out bytes.Buffer
b := bytes.NewReader(msgData)
r, err := zlib.NewReader(b)
if err != nil {
return nil, nil, err
}
defer r.Close()
if _, err := io.Copy(&out, r); err != nil {
return nil, nil, err
}
return &header, out.Bytes(), nil
}
return &header, msgData, nil
}
// Connect 连接券商行情服务器
func (client *Client) Connect() (*proto.Hello1Reply, error) {
if client.mode == clientModeEx {
client.mu.Lock()
if client.main == nil {
client.main = newClientWithOptions(client.opt, clientModeMain)
}
main := client.main
client.mu.Unlock()
return main.Connect()
}
client.mu.Lock()
defer client.mu.Unlock()
obj := proto.NewHello1()
var reply *proto.Hello1Reply
err := client.connectWithHandshake(func() error {
var err error
reply, err = executeProtocolLocked(client, obj)
return err
})
if err != nil {
return nil, err
}
return reply, nil
}
// ConnectEx 连接扩展市场服务器并完成登录
func (client *Client) ConnectEx() (*proto.ExLoginReply, error) {
if client.mode == clientModeMain {
client.mu.Lock()
if client.ex == nil {
client.ex = newClientWithOptions(client.opt, clientModeEx)
}
ex := client.ex
client.mu.Unlock()
return ex.ConnectEx()
}
client.mu.Lock()
defer client.mu.Unlock()
obj := proto.NewExLogin()
var reply *proto.ExLoginReply
err := client.connectWithHandshake(func() error {
var err error
reply, err = executeProtocolLocked(client, obj)
return err
})
if err != nil {
return nil, err
}
return reply, nil
}
// Disconnect 断开服务器
func (client *Client) Disconnect() error {
client.mu.Lock()
conn := client.conn
client.conn = nil
main := client.main
ex := client.ex
client.main = nil
client.ex = nil
client.mu.Unlock()
var err error
if conn != nil {
err = conn.Close()
}
if main != nil && main != client {
if closeErr := main.Disconnect(); err == nil {
err = closeErr
}
}
if ex != nil && ex != client && ex != main {
if closeErr := ex.Disconnect(); err == nil {
err = closeErr
}
}
return err
}