-
Notifications
You must be signed in to change notification settings - Fork 2
/
conn.go
76 lines (63 loc) · 1.21 KB
/
conn.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
package statsd
import (
"net"
"sync"
"time"
)
var (
dialTimeout = net.DialTimeout
)
type clientConn struct {
network, addr string
c *Client
conn net.Conn
mu sync.Mutex
buf []byte
}
func newClientConn(network, addr string, c *Client) (*clientConn, error) {
conn, err := dialTimeout(network, addr, c.opts.timeout)
if err != nil {
return nil, err
}
cc := &clientConn{
network: network,
addr: addr,
c: c,
conn: conn,
buf: make([]byte, 0, c.opts.maxPacketSize),
}
go func() {
ticker := time.NewTicker(c.opts.flushPeriod)
for _ = range ticker.C {
cc.mu.Lock()
cc.flush()
cc.mu.Unlock()
}
}()
return cc, nil
}
func (cc *clientConn) write(b []byte) {
cc.mu.Lock()
if len(cc.buf)+len(b) > cap(cc.buf) {
cc.flush()
}
cc.buf = append(cc.buf, b...)
cc.mu.Unlock()
}
func (cc *clientConn) flush() {
if len(cc.buf) == 0 {
return
}
_, err := cc.conn.Write(cc.buf[:len(cc.buf)])
cc.handleError(err)
cc.buf = cc.buf[:0]
}
func (cc *clientConn) handleError(err error) {
if err == nil {
return
}
if cc.c.opts.errHandler != nil {
cc.c.opts.errHandler(err)
}
// TODO: reconnect if network net is a stream-orientend network: "tcp", "tcp4"
}