v2
lizifeng 2023-04-18 11:07:36 +08:00
parent ac53e3fe9a
commit ebcb0f87a2
1 changed files with 25 additions and 39 deletions

View File

@ -9,23 +9,17 @@ import (
"time" "time"
) )
var (
wg = &sync.WaitGroup{}
)
func Run() { func Run() {
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
for name, item := range ProxyMap { for name, item := range ProxyMap {
wg.Add(1)
go listenTcp(name, item) go listenTcp(name, item)
} }
wg.Wait() select {}
} }
func listenTcp(name string, item ProxyItem) { func listenTcp(name string, item ProxyItem) {
defer wg.Done()
listen, err := net.Listen("tcp", item.LocalAddr) listen, err := net.Listen("tcp", item.LocalAddr)
if err != nil { if err != nil {
@ -36,56 +30,48 @@ func listenTcp(name string, item ProxyItem) {
mylog.Infof("[%s] listen %s", name, item.LocalAddr) mylog.Infof("[%s] listen %s", name, item.LocalAddr)
for { for {
conn, err := listen.Accept() localConn, err := listen.Accept()
if err != nil { if err != nil {
mylog.Errorf("conn accept err: %s", item.LocalAddr, err) mylog.Errorf("conn accept err: %s", item.LocalAddr, err)
return return
} }
go proxyTcp(conn, item) go proxyTcp(localConn, item)
} }
} }
func proxyTcp(conn net.Conn, item ProxyItem) { func proxyTcp(localConn net.Conn, item ProxyItem) {
randRemoteAddr := item.RemoteAddr[rand.Intn(len(item.RemoteAddr))] randRemoteAddr := item.RemoteAddr[rand.Intn(len(item.RemoteAddr))]
remoteConn, err := net.Dial("tcp", randRemoteAddr) remoteConn, err := net.DialTimeout("tcp", randRemoteAddr, time.Second*3)
if err != nil { if err != nil {
mylog.Errorf("connect remote err: %s\n", err) localConn.Close()
mylog.Errorf("connect remote err: %s", err)
return return
} }
go copyConn(randRemoteAddr, conn, remoteConn) mylog.Infof("start proxy %s -> %s", localConn.RemoteAddr(), randRemoteAddr)
wg0 := &sync.WaitGroup{}
wg0.Add(2)
go copyConn(wg0, localConn, remoteConn)
go copyConn(wg0, remoteConn, localConn)
wg0.Wait()
mylog.Infof("stop proxy %s -> %s", localConn.RemoteAddr(), randRemoteAddr)
} }
func copyConn(addr string, conn, remoteConn net.Conn) { func copyConn(wg0 *sync.WaitGroup, localConn, remoteConn net.Conn) {
mylog.Infof("start proxy: %s", addr) defer func() {
wg0.Done()
wg2 := &sync.WaitGroup{} localConn.Close()
wg2.Add(2) remoteConn.Close()
go func() {
_, err := io.Copy(conn, remoteConn)
if err != nil {
mylog.Error(err)
return
}
wg2.Done()
}() }()
go func() { _, err := io.Copy(remoteConn, localConn)
_, err := io.Copy(remoteConn, conn) if err != nil {
if err != nil { mylog.Error(err)
mylog.Error(err) }
return
}
wg2.Done()
}()
wg2.Wait()
mylog.Infof("stop proxy: %s", addr)
} }