-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpconn.go
61 lines (54 loc) · 1.19 KB
/
pconn.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
package main
import (
"net"
"time"
)
const tcpDialTimeout = 10 * time.Second
// A PConn is a persistent TCP connection. It opens a connection lazily when
// used and reopens the connection on errors.
// It can also be thought of as a connection pool of size 1.
type PConn struct {
c *net.TCPConn
addr string
}
func DialPConn(addr string) *PConn {
return &PConn{addr: addr}
}
func (c *PConn) connect() error {
conn, err := net.DialTimeout("tcp", c.addr, tcpDialTimeout)
if err != nil {
return err
}
c.c = conn.(*net.TCPConn)
if err := c.c.SetKeepAlivePeriod(tcpKeepAlivePeriod); err != nil {
return err
}
return c.c.SetKeepAlive(true)
}
func (c *PConn) Write(b []byte) (int, error) {
// For now, just do one retry -- we could introduce more with backoff,
// etc later.
hadConn := c.c != nil
if c.c == nil {
if err := c.connect(); err != nil {
return 0, err
}
}
n, err := c.c.Write(b)
if err != nil {
// TODO: I could convert to net.Error and check Timeout() and/or
// Temporary() -- is that useful?
if hadConn {
c.c.Close()
c.c = nil
return c.Write(b)
}
}
return n, err
}
func (c *PConn) Close() error {
if c.c != nil {
return c.c.Close()
}
return nil
}