-
Notifications
You must be signed in to change notification settings - Fork 59
/
connection.go
89 lines (69 loc) · 1.9 KB
/
connection.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
/* connection handle the tcp socket to the TWS or IB Gateway*/
package ibapi
import (
"net"
"strconv"
"go.uber.org/zap"
)
// IbConnection wrap the tcp connection with TWS or Gateway
type IbConnection struct {
*net.TCPConn
host string
port int
clientID int64
state int
numBytesSent int
numMsgSent int
numBytesRecv int
numMsgRecv int
}
func (ibconn *IbConnection) Write(bs []byte) (int, error) {
n, err := ibconn.TCPConn.Write(bs)
ibconn.numBytesSent += n
ibconn.numMsgSent++
log.Debug("conn write", zap.Int("nBytes", n))
return n, err
}
func (ibconn *IbConnection) Read(bs []byte) (int, error) {
n, err := ibconn.TCPConn.Read(bs)
ibconn.numBytesRecv += n
ibconn.numMsgRecv++
log.Debug("conn read", zap.Int("nBytes", n))
return n, err
}
func (ibconn *IbConnection) setState(state int) {
ibconn.state = state
}
func (ibconn *IbConnection) reset() {
ibconn.numBytesSent = 0
ibconn.numBytesRecv = 0
ibconn.numMsgSent = 0
ibconn.numMsgRecv = 0
}
func (ibconn *IbConnection) disconnect() error {
log.Debug("conn disconnect",
zap.Int("nMsgSent", ibconn.numMsgSent),
zap.Int("nBytesSent", ibconn.numBytesSent),
zap.Int("nMsgRecv", ibconn.numMsgRecv),
zap.Int("nBytesRecv", ibconn.numBytesRecv),
)
return ibconn.Close()
}
func (ibconn *IbConnection) connect(host string, port int) error {
var err error
var addr *net.TCPAddr
ibconn.host = host
ibconn.port = port
ibconn.reset()
server := ibconn.host + ":" + strconv.Itoa(port)
if addr, err = net.ResolveTCPAddr("tcp4", server); err != nil {
log.Error("failed to resove tcp address", zap.Error(err), zap.String("host", server))
return err
}
if ibconn.TCPConn, err = net.DialTCP("tcp4", nil, addr); err != nil {
log.Error("failed to dial tcp", zap.Error(err), zap.Any("address", addr))
return err
}
log.Debug("tcp socket connected", zap.Any("address", ibconn.TCPConn.RemoteAddr()))
return err
}