-
Notifications
You must be signed in to change notification settings - Fork 0
/
netclient.go
199 lines (179 loc) · 5.42 KB
/
netclient.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
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
/*
MIT License
Copyright (c) 2015-2017 University Corporation for Atmospheric Research
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package agnoio
import (
"context"
"fmt"
"net"
"regexp"
"time"
)
var (
_ IDoIO = &NetClient{}
netClientRe = regexp.MustCompile("^(tcp|tcp4|tcp6|udp|udp4|udp6):\\/\\/(.*:[a-zA-Z0-9]*)$")
writeErr = newErr(false, false, fmt.Errorf("write: broken connection"))
readErr = newErr(false, false, fmt.Errorf("read: broken connection"))
)
/*
NewNetClient opens a connection to remote tcpv4 host.
dial should be in the form of: 'tcp|udp[46]{0,1}://<host>:<port>'
Timeout is used a read/write timeout at the socket level. If timeout is zero,
timeouts are not used nor applied, and any errors are due to normal socket behaviour.
If timeout is greater than zero, a deadline is set on every Read() and Write()
function. In this case, Read() and Write() will return a timeout error that
should be checked via something like the following:
io := NewNetClient(ctx, 100 * time.Millisecond, "tcp://localhost:4242")
...
n, e := io.Write(b)
switch e {
case io.EOF: // Broken socket
...
default:
if nerr, ok := e.(net.Error); ok {
if nerr.Temporary() { //Temporary error
...
}
if nerr.Timeout() { //Timeout error from enforced deadline
...
}
}
}
The caller is responsible for handling errors. This pkg just propagates any error
encountered.
*/
func NewNetClient(ctx context.Context, timeout time.Duration, dial string) (*NetClient, error) {
if !netClientRe.MatchString(dial) {
return nil, newErr(false, false, fmt.Errorf("dial string not in correct form"))
}
matches := netClientRe.FindAllStringSubmatch(dial, -1) //capture groups used
nctx, cancel := context.WithCancel(ctx)
nc := &NetClient{
network: matches[0][1],
address: matches[0][2],
timeout: timeout,
rwtimeout: 1 * time.Millisecond,
ctx: nctx,
cancel: cancel,
}
return nc, nc.Open()
}
/*
NetClient provides an implementer of the IDoIO interface. It provides
access under the following URI Regimes:
tcp://
tcp4://
tcp6://
udp://
udp4://
udp6://
*/
type NetClient struct {
network, address string
cancel context.CancelFunc
ctx context.Context
rwtimeout time.Duration
timeout time.Duration
conn net.Conn
}
/*
String conforms to the fmt.Stringer interface. Prints something like
tcp6 connection to tcp6://localhost::8080
which meant as a human comprehendable explanation of the connection
*/
func (nc *NetClient) String() string {
return fmt.Sprintf("%v connection to %v", nc.network, nc.address)
}
/*
Open forcible disconnects (ignore errors) the network connection and
attempts the connect process again. It returns an error if it was unable to start
*/
func (nc *NetClient) Open() (err error) {
select {
case <-nc.ctx.Done():
return newErr(false, false, nc.ctx.Err())
default:
}
if nc.conn != nil {
nc.conn.Close()
nc.conn = nil
}
dialer := net.Dialer{
Timeout: nc.timeout,
// Deadline:
// LocalAddr:
// FallbackDelay:
DualStack: false,
KeepAlive: 1 * time.Second,
Resolver: nil,
}
//Errors from DialContext implement net.Error
nc.conn, err = dialer.DialContext(nc.ctx, nc.network, nc.address)
return
}
/*
Read conforms to io.Writer, but immediately returns upon ctx
destruction after closing the underlying transport
*/
func (nc *NetClient) Read(b []byte) (int, error) {
select {
case <-nc.ctx.Done():
defer nc.Close()
return 0, newErr(false, false, nc.ctx.Err())
default:
if nc.conn == nil {
return 0, readErr
}
if nc.rwtimeout > 0 {
nc.conn.SetReadDeadline(time.Now().Add(nc.rwtimeout))
}
return nc.conn.Read(b) //nc.conn return errors that conform to net.Error
}
}
/*
Write conforms to io.Writer, but immediately returns upon ctx
destruction after closing the underlying transport
*/
func (nc *NetClient) Write(b []byte) (int, error) {
select {
case <-nc.ctx.Done():
defer nc.Close()
return 0, newErr(false, false, nc.ctx.Err())
default:
if nc.conn == nil {
return 0, writeErr
}
if nc.rwtimeout > 0 {
nc.conn.SetWriteDeadline(time.Now().Add(nc.rwtimeout))
}
return nc.conn.Write(b) //nc.conn return errors that conform to net.Error
}
}
/*
Close conforms to io.Closer, but immediately returns upon ctx
destruction after closing the underlying transport
*/
func (nc *NetClient) Close() error {
nc.cancel()
defer func() { nc.conn = nil }()
if nc.conn != nil {
return nc.conn.Close()
}
return nil
}