-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.go
109 lines (82 loc) · 1.6 KB
/
tcp.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
package pool
import (
"fmt"
"net"
"sync"
"time"
)
type TCPClient struct {
*net.TCPConn
mu sync.RWMutex
network string
laddr *net.TCPAddr
raddr *net.TCPAddr
maxRetries int
retryInterval time.Duration
}
func newTCPClient(network string, laddr, raddr *net.TCPAddr) *TCPClient {
client := &TCPClient{
TCPConn: nil,
mu: sync.RWMutex{},
network: network,
laddr: laddr,
raddr: raddr,
maxRetries: 10,
retryInterval: 10 * time.Millisecond,
}
// error is ignored
_ = client.reconnect()
return client
}
func (c *TCPClient) SetMaxRetries(maxRetries int) {
c.mu.Lock()
defer c.mu.Unlock()
c.maxRetries = maxRetries
}
func (c *TCPClient) SetRetryInterval(retryInterval time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.retryInterval = retryInterval
}
func (c *TCPClient) reconnect() error {
c.mu.Lock()
defer c.mu.Unlock()
conn, err := net.DialTCP(c.network, c.laddr, c.raddr)
if err != nil {
return err
}
_ = conn.CloseRead()
if c.TCPConn != nil {
_ = c.TCPConn.Close()
}
c.TCPConn = conn
return nil
}
func (c *TCPClient) Write(b []byte) (int, error) {
c.mu.RLock()
defer c.mu.RUnlock()
disconnected := c.TCPConn == nil
t := c.retryInterval
for i := 0; i < c.maxRetries; i++ {
// reconnect
if disconnected {
if i > 0 {
time.Sleep(t)
}
c.mu.RUnlock()
err := c.reconnect()
c.mu.RLock()
if err != nil {
disconnected = true
continue
}
}
// won't be executed if the connection failed
n, err := c.TCPConn.Write(b)
if err == nil {
return n, err
}
disconnected = true
}
return -1, fmt.Errorf("ErrMaxRetries")
}