-
Notifications
You must be signed in to change notification settings - Fork 61
/
proxy.go
107 lines (88 loc) · 2.08 KB
/
proxy.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
// zheng-ji.info
package main
import (
"net"
"time"
)
func initProxy() {
pLog.Infof("Proxying %s -> %s\n", pConfig.Bind, pConfig.Backend)
server, err := net.Listen("tcp", pConfig.Bind)
if err != nil {
pLog.Fatal(err)
}
waitQueue := make(chan net.Conn, pConfig.WaitQueueLen)
availPools := make(chan bool, pConfig.MaxConn)
for i := 0; i < pConfig.MaxConn; i++ {
availPools <- true
}
go loop(waitQueue, availPools)
for {
connection, err := server.Accept()
if err != nil {
pLog.Error(err)
} else {
pLog.Infof("Received connection from %s.\n", connection.RemoteAddr())
waitQueue <- connection
}
}
}
func loop(waitQueue chan net.Conn, availPools chan bool) {
for connection := range waitQueue {
<-availPools
go func(connection net.Conn) {
handleConnection(connection)
availPools <- true
pLog.Infof("Closed connection from %s.\n", connection.RemoteAddr())
}(connection)
}
}
func handleConnection(connection net.Conn) {
defer connection.Close()
bksvr, ok := getBackendSvr(connection)
if !ok {
return
}
remote, err := net.Dial("tcp", bksvr.svrStr)
if err != nil {
pLog.Error(err)
bksvr.failTimes++
return
}
//等待双向连接完成
complete := make(chan bool, 2)
oneSide := make(chan bool, 1)
otherSide := make(chan bool, 1)
go pass(connection, remote, complete, oneSide, otherSide)
go pass(remote, connection, complete, otherSide, oneSide)
<-complete
<-complete
remote.Close()
}
// copy Content two-way
func pass(from net.Conn, to net.Conn, complete chan bool, oneSide chan bool, otherSide chan bool) {
var err error
var read int
bytes := make([]byte, 256)
for {
select {
case <-otherSide:
complete <- true
return
default:
from.SetReadDeadline(time.Now().Add(time.Duration(pConfig.Timeout) * time.Second))
read, err = from.Read(bytes)
if err != nil {
complete <- true
oneSide <- true
return
}
to.SetWriteDeadline(time.Now().Add(time.Duration(pConfig.Timeout) * time.Second))
_, err = to.Write(bytes[:read])
if err != nil {
complete <- true
oneSide <- true
return
}
}
}
}