-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
103 lines (85 loc) · 1.77 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
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
package trafficshaper
import (
"net"
"time"
"github.com/smallinsky/trafficshaper/bandwidth"
)
const (
maxChunkSize = 1024 * 64 // 64 KB
)
var _ net.Conn = (*connProxy)(nil)
type connProxy struct {
c net.Conn
bs bandwidth.Shaper
}
func (c *connProxy) Read(b []byte) (int, error) {
chunkSize := c.bs.GetDLCapaity(c)
if chunkSize > maxChunkSize {
chunkSize = maxChunkSize
}
i := 0
sum := 0
for ; i < len(b)/int(chunkSize); i++ {
n, err := c.c.Read(b[i*int(chunkSize) : (i+1)*int(chunkSize)])
if err != nil {
return sum, err
}
c.bs.LimitDL(c, chunkSize)
sum += n
}
if sum != len(b) {
left := len(b) - sum
c.bs.LimitDL(c, int64(left))
n, err := c.c.Read(b[sum:len(b)])
if err != nil {
return sum, err
}
sum += n
}
return sum, nil
}
func (c *connProxy) Write(b []byte) (int, error) {
chunkSize := c.bs.GetULCapaity(c)
if chunkSize > maxChunkSize {
chunkSize = maxChunkSize
}
i := 0
sum := 0
for ; i < len(b)/int(chunkSize); i++ {
n, err := c.c.Write(b[i*int(chunkSize) : (i+1)*int(chunkSize)])
if err != nil {
return sum, err
}
c.bs.LimitUL(c, chunkSize)
sum += n
}
if sum != len(b) {
left := len(b) - sum
c.bs.LimitUL(c, int64(left))
n, err := c.c.Write(b[sum:len(b)])
if err != nil {
return sum, err
}
sum += n
}
return sum, nil
}
func (c *connProxy) Close() error {
c.bs.RemoveConn(c)
return c.c.Close()
}
func (c *connProxy) LocalAddr() net.Addr {
return c.c.LocalAddr()
}
func (c *connProxy) RemoteAddr() net.Addr {
return c.c.RemoteAddr()
}
func (c *connProxy) SetDeadline(t time.Time) error {
return c.c.SetDeadline(t)
}
func (c *connProxy) SetReadDeadline(t time.Time) error {
return c.c.SetReadDeadline(t)
}
func (c *connProxy) SetWriteDeadline(t time.Time) error {
return c.c.SetWriteDeadline(t)
}