-
Notifications
You must be signed in to change notification settings - Fork 21
/
stratum_client.go
89 lines (76 loc) · 1.48 KB
/
stratum_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
package main
import (
"context"
"encoding/json"
"io"
"net"
)
type nodeClient struct {
conf *config
c net.Conn
enc *json.Encoder
dec *json.Decoder
}
func initNodeStratumClient(conf *config) *nodeClient {
ip := net.ParseIP(conf.Node.Address)
raddr := &net.TCPAddr{
IP: ip,
Port: conf.Node.StratumPort,
}
conn, err := net.DialTCP("tcp4", nil, raddr)
if err != nil {
log.Error(err)
}
enc := json.NewEncoder(conn)
dec := json.NewDecoder(conn)
nc := &nodeClient{
conf: conf,
c: conn,
enc: enc,
dec: dec,
}
return nc
}
// registerHandler will hook the callback function to the tcp conn, and call func when recv
func (nc *nodeClient) registerHandler(ctx context.Context, callback func(sr json.RawMessage)) {
for {
select {
case <-ctx.Done():
return
default:
var sr json.RawMessage
err := nc.dec.Decode(&sr)
if err != nil {
log.Error(err)
if err == io.EOF {
if nc.reconnect() != nil {
return
}
}
continue
}
resp, _ := sr.MarshalJSON()
log.Infof("Node returns a response: %s", resp)
go callback(sr)
}
}
}
func (nc *nodeClient) reconnect() error {
ip := net.ParseIP(nc.conf.Node.Address)
raddr := &net.TCPAddr{
IP: ip,
Port: nc.conf.Node.StratumPort,
}
conn, err := net.DialTCP("tcp4", nil, raddr)
if err != nil {
log.Error(err)
return err
}
nc.c = conn
nc.enc = json.NewEncoder(conn)
nc.dec = json.NewDecoder(conn)
return nil
}
func (nc *nodeClient) close() {
_ = nc.c.Close()
}