From 0caa8e05a32e3c92b8b09070485817221bfa6af5 Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Mon, 17 Sep 2018 00:15:58 +0800 Subject: [PATCH] Improve: better relay copies --- tunnel/connection.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/tunnel/connection.go b/tunnel/connection.go index 27a24a42..87d85d3f 100644 --- a/tunnel/connection.go +++ b/tunnel/connection.go @@ -3,6 +3,7 @@ package tunnel import ( "bufio" "io" + "net" "net/http" "github.com/Dreamacro/clash/adapters/local" @@ -56,6 +57,18 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter) func (t *Tunnel) handleSOCKS(request *adapters.SocketAdapter, proxy C.ProxyAdapter) { conn := newTrafficTrack(proxy.Conn(), t.traffic) - go io.Copy(request.Conn(), conn) - io.Copy(conn, request.Conn()) + relay(request.Conn(), conn) +} + +// relay copies between left and right bidirectionally. +func relay(leftConn, rightConn net.Conn) { + ch := make(chan error) + + go func() { + _, err := io.Copy(leftConn, rightConn) + ch <- err + }() + + io.Copy(rightConn, leftConn) + <-ch }