@@ -5,36 +5,53 @@ import (
55 "log"
66 "net"
77 "strconv"
8+ "strings"
89 "time"
910
1011 "github.com/leviathan1995/spleen/service"
1112)
1213
1314type client struct {
1415 * service.Service
15- srvAddr * net.TCPAddr
16+ srvAddr * net.TCPAddr
17+ limitRate map [int64 ]int64
1618}
1719
18- func NewClient (serverIP string , serverPort int ) * client {
20+ func NewClient (serverIP string , serverPort int , limitRate [] string ) * client {
1921 srvAddr , _ := net .ResolveTCPAddr ("tcp" , serverIP + ":" + strconv .Itoa (serverPort ))
22+ limits := make (map [int64 ]int64 )
23+ for _ , rates := range limitRate {
24+ rate := strings .Split (rates , ":" )
25+ port , _ := strconv .Atoi (rate [0 ])
26+ speed , _ := strconv .Atoi (rate [1 ])
27+ limits [int64 (port )] = int64 (speed )
28+ }
29+
2030 return & client {
2131 & service.Service {},
2232 srvAddr ,
33+ limits ,
2334 }
2435}
2536
2637func (c * client ) Run () {
38+ for port , rate := range c .limitRate {
39+ log .Printf ("The limiting rate configurations Port: %d, Speed: %d KB/s" , port , rate )
40+ }
41+
2742 for {
2843 if len (connectionPool ) < 10 {
29- srvConn , err := c .DialSrv ()
30- if err != nil {
31- log .Printf ("Connect to the server %s:%d failed: %s. \n " , c .srvAddr .IP .String (), c .srvAddr .Port , err )
32- continue
44+ for i := len (connectionPool ); i < 10 ; i ++ {
45+ srvConn , err := c .DialSrv ()
46+ if err != nil {
47+ log .Printf ("Connect to the server %s:%d failed: %s. \n " , c .srvAddr .IP .String (), c .srvAddr .Port , err )
48+ continue
49+ }
50+ log .Printf ("Connect to the server %s:%d successful.\n " , c .srvAddr .IP .String (), c .srvAddr .Port )
51+ srvConn .SetKeepAlive (true )
52+ connectionPool <- srvConn
53+ go c .handleConn (srvConn )
3354 }
34- log .Printf ("Connect to the server %s:%d successful.\n " , c .srvAddr .IP .String (), c .srvAddr .Port )
35- srvConn .SetKeepAlive (true )
36- connectionPool <- srvConn
37- go c .handleConn (srvConn )
3855 } else {
3956 time .Sleep (1 * time .Second )
4057 }
@@ -75,15 +92,22 @@ func (c *client) handleConn(srvConn *net.TCPConn) {
7592 } else {
7693 log .Printf ("Connect to the destination address localhost:%d successful." , dstAddr .Port )
7794 }
78-
7995 defer dstConn .Close ()
96+
97+ dstConn .SetKeepAlive (true )
8098 _ = dstConn .SetLinger (0 )
8199
100+ var limitRate int64
101+
102+ if rate , found := c .limitRate [port ]; found {
103+ limitRate = rate * 1024 /* bytes */
104+ }
105+
82106 go func () {
83- errTransfer := c .TransferToTCP (dstConn , srvConn )
107+ errTransfer := c .TransferToTCP (dstConn , srvConn , limitRate )
84108 if errTransfer != nil {
85109 return
86110 }
87111 }()
88- err = c .TransferToTCP (srvConn , dstConn )
112+ err = c .TransferToTCP (srvConn , dstConn , 0 )
89113}
0 commit comments