-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
183 lines (155 loc) · 4.13 KB
/
client.go
File metadata and controls
183 lines (155 loc) · 4.13 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
package sockit
import (
"crypto/tls"
"net"
"time"
"github.com/sirupsen/logrus"
)
type Client struct {
mgr ConnManager
codec Codec
opts *NewClientOptions
closed chan struct{}
}
type NewClientOptions struct {
EnableKeepalive bool
KeepalivePeriod time.Duration
HeartbeatPacketFactory func() Packet
OnConnected func(c Conn) error
OnSessionCreated func(s *Session)
OnClosed func(session *Session)
NeedReconnect bool
ReconnectPolicy ReconnectPolicy
}
func NewClient(codec Codec, handler Handler, opts *NewClientOptions) *Client {
if opts == nil {
opts = &NewClientOptions{
EnableKeepalive: false,
NeedReconnect: false,
}
}
cli := &Client{
opts: opts,
codec: codec,
closed: make(chan struct{}),
}
cli.mgr = NewManager(handler, &NewManagerOptions{
OnSessionCreated: opts.OnSessionCreated,
AfterSessionClosed: func(s *Session) {
cli.reconnect(s)
},
})
if cli.opts.EnableKeepalive {
go cli.heartbeat()
}
return cli
}
func (cli *Client) Dial(network string, addr string) (*Session, error) {
c, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
conn := newConn(c, cli.codec)
if cli.opts.OnConnected != nil {
if err := cli.opts.OnConnected(conn); err != nil {
return nil, err
}
}
return cli.mgr.StoreConn(conn)
}
func (cli *Client) DialTLS(network string, addr string, config *tls.Config) (*Session, error) {
c, err := tls.Dial(network, addr, config)
if err != nil {
return nil, err
}
conn := newConn(c, cli.codec)
if cli.opts.OnConnected != nil {
if err := cli.opts.OnConnected(conn); err != nil {
return nil, err
}
}
return cli.mgr.StoreConn(conn)
}
func (cli *Client) DialTimeout(network string, addr string, timeout time.Duration) (*Session, error) {
c, err := net.DialTimeout(network, addr, timeout)
if err != nil {
return nil, err
}
conn := newConn(c, cli.codec)
if cli.opts.OnConnected != nil {
if err := cli.opts.OnConnected(conn); err != nil {
return nil, err
}
}
return cli.mgr.StoreConn(conn)
}
type ReconnectPolicy interface {
Retry() bool
Timer() *time.Timer
}
func (cli *Client) reconnect(sess *Session) {
addr := sess.RemoteAddr()
policy := cli.opts.ReconnectPolicy
for cli.needReconnect(sess) && policy.Retry() {
logrus.WithField("sessionId", sess.id).WithField("remoteAddr", sess.RemoteAddr().String()).Debugln("session reconnect")
if s, err := cli.DialTimeout(addr.Network(), addr.String(), time.Second*5); err == nil {
s.data = sess.data
s.user = sess.user
s.lastPackTs = sess.lastPackTs
s.requests = sess.requests
*sess = *s // replace old session
logrus.WithFields(logrus.Fields{"remoteAddr": sess.RemoteAddr().String(), "sessionId": sess.id}).Debugln("reconnect successful")
return
} else {
logrus.WithFields(logrus.Fields{
"remoteAddr": sess.RemoteAddr().String(),
"sessionId": sess.id,
}).Errorln("reconnect error", err)
}
timer := policy.Timer()
select {
case <-cli.closed:
timer.Stop()
return
case <-timer.C:
timer.Stop()
}
}
}
func (cli *Client) needReconnect(sess *Session) bool {
if !cli.opts.NeedReconnect {
return false
}
return !sess.manuallyClosed
}
func (cli *Client) heartbeat() {
ticker := time.NewTicker(cli.opts.KeepalivePeriod)
for {
select {
case <-ticker.C:
cli.mgr.RangeSession(func(s *Session) {
if err := s.SendPacket(cli.opts.HeartbeatPacketFactory()); err != nil {
logrus.WithFields(logrus.Fields{
"sessionId": s.Id(),
"remoteAddr": s.RemoteAddr().String(),
}).Errorln("send heartbeat packet error:", err.Error())
if err := cli.mgr.RemoveSession(s.Id()); err != nil {
logrus.WithFields(logrus.Fields{
"sessionId": s.Id(),
"remoteAddr": s.RemoteAddr().String(),
}).Errorln("remove session error:", err.Error())
}
}
})
case <-cli.closed:
ticker.Stop()
return
}
}
}
func (cli *Client) FindSession(id int64) (*Session, bool) { return cli.mgr.FindSession(id) }
func (cli *Client) RangeSession(fn func(sess *Session)) { cli.mgr.RangeSession(fn) }
func (cli *Client) Close() error {
close(cli.closed)
return cli.mgr.Close()
}