optimize proxy

This commit is contained in:
Jason
2019-08-13 22:58:10 +08:00
parent 31cca563c9
commit fd17490ca1
3 changed files with 71 additions and 64 deletions

View File

@@ -1,12 +1,8 @@
package proxy
import (
"io"
"net"
"sync"
"time"
"github.com/xjasonlyu/tun2socks/common/pool"
)
type duplexConn interface {
@@ -33,47 +29,3 @@ func tcpKeepAlive(conn net.Conn) {
tcp.SetKeepAlivePeriod(30 * time.Second)
}
}
func tcpRelay(localConn, remoteConn net.Conn) {
var once sync.Once
closeOnce := func() {
once.Do(func() {
localConn.Close()
remoteConn.Close()
})
}
// Close
defer closeOnce()
// WaitGroup
var wg sync.WaitGroup
wg.Add(1)
// Up Link
go func() {
buf := pool.BufPool.Get().([]byte)
defer pool.BufPool.Put(buf[:cap(buf)])
if _, err := io.CopyBuffer(remoteConn, localConn, buf); err != nil {
closeOnce()
} else {
localConn.SetDeadline(time.Now())
remoteConn.SetDeadline(time.Now())
tcpCloseRead(remoteConn)
}
wg.Done()
}()
// Down Link
buf := pool.BufPool.Get().([]byte)
if _, err := io.CopyBuffer(localConn, remoteConn, buf); err != nil {
closeOnce()
} else {
localConn.SetDeadline(time.Now())
remoteConn.SetDeadline(time.Now())
tcpCloseRead(localConn)
}
pool.BufPool.Put(buf[:cap(buf)])
wg.Wait() // Wait for Up Link done
}