From f4c51cdb0ef32fb982126f44046c3399ac6379f1 Mon Sep 17 00:00:00 2001 From: Dreamacro <305009791@qq.com> Date: Wed, 29 Aug 2018 15:00:12 +0800 Subject: [PATCH] Improve: Better handling of TCP connections --- adapters/remote/direct.go | 2 +- adapters/remote/shadowsocks.go | 2 +- adapters/remote/socks5.go | 3 +-- adapters/remote/util.go | 7 +++++++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/adapters/remote/direct.go b/adapters/remote/direct.go index ac46c4a7..9d22f948 100644 --- a/adapters/remote/direct.go +++ b/adapters/remote/direct.go @@ -36,7 +36,7 @@ func (d *Direct) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) { if err != nil { return } - c.(*net.TCPConn).SetKeepAlive(true) + tcpKeepAlive(c) return &DirectAdapter{conn: c}, nil } diff --git a/adapters/remote/shadowsocks.go b/adapters/remote/shadowsocks.go index 6323a897..07590c9d 100644 --- a/adapters/remote/shadowsocks.go +++ b/adapters/remote/shadowsocks.go @@ -46,7 +46,7 @@ func (ss *ShadowSocks) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err erro if err != nil { return nil, fmt.Errorf("%s connect error", ss.server) } - c.(*net.TCPConn).SetKeepAlive(true) + tcpKeepAlive(c) c = ss.cipher.StreamConn(c) _, err = c.Write(serializesSocksAddr(addr)) return &ShadowsocksAdapter{conn: c}, err diff --git a/adapters/remote/socks5.go b/adapters/remote/socks5.go index dec9adde..8d82f183 100644 --- a/adapters/remote/socks5.go +++ b/adapters/remote/socks5.go @@ -44,8 +44,7 @@ func (ss *Socks5) Generator(addr *C.Addr) (adapter C.ProxyAdapter, err error) { if err != nil { return nil, fmt.Errorf("%s connect error", ss.addr) } - c.(*net.TCPConn).SetKeepAlive(true) - + tcpKeepAlive(c) if err := ss.sharkHand(addr, c); err != nil { return nil, err } diff --git a/adapters/remote/util.go b/adapters/remote/util.go index 02c084bc..e8a35006 100644 --- a/adapters/remote/util.go +++ b/adapters/remote/util.go @@ -84,3 +84,10 @@ func selectFast(in chan interface{}) chan interface{} { return out } + +func tcpKeepAlive(c net.Conn) { + if tcp, ok := c.(*net.TCPConn); ok { + tcp.SetKeepAlive(true) + tcp.SetKeepAlivePeriod(3 * time.Minute) + } +}