From 75e83adfba0670573ff39e21df45cf90d9ef10df Mon Sep 17 00:00:00 2001 From: xtaci Date: Mon, 22 Apr 2019 14:10:12 +0800 Subject: [PATCH] reuse buffer for io.copyBuffer --- client/main.go | 23 ++++++++++++++++------- server/main.go | 23 ++++++++++++++++------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/client/main.go b/client/main.go index c9807ed..c795216 100644 --- a/client/main.go +++ b/client/main.go @@ -9,6 +9,7 @@ import ( "math/rand" "net" "os" + "sync" "time" "golang.org/x/crypto/pbkdf2" @@ -22,12 +23,14 @@ import ( "path/filepath" ) -var ( - // VERSION is injected by buildflags - VERSION = "SELFBUILD" - // SALT is use for pbkdf2 key expansion - SALT = "kcp-go" -) +// SALT is use for pbkdf2 key expansion +const SALT = "kcp-go" + +// VERSION is injected by buildflags +var VERSION = "SELFBUILD" + +// A pool for stream copying +var xmitBuf sync.Pool type compStream struct { conn net.Conn @@ -74,7 +77,9 @@ func handleClient(sess *smux.Session, p1 io.ReadWriteCloser, quiet bool) { streamCopy := func(dst io.Writer, src io.Reader) chan struct{} { die := make(chan struct{}) go func() { - io.CopyBuffer(dst, src, make([]byte, 65535)) + buf := xmitBuf.Get().([]byte) + io.CopyBuffer(dst, src, buf) + xmitBuf.Put(buf) close(die) }() return die @@ -99,6 +104,10 @@ func main() { // add more log flags for debugging log.SetFlags(log.LstdFlags | log.Lshortfile) } + xmitBuf.New = func() interface{} { + return make([]byte, 65535) + } + myApp := cli.NewApp() myApp.Name = "kcptun" myApp.Usage = "client(with SMUX)" diff --git a/server/main.go b/server/main.go index e5900e6..6f66c23 100644 --- a/server/main.go +++ b/server/main.go @@ -11,6 +11,7 @@ import ( "net/http" _ "net/http/pprof" "os" + "sync" "time" "golang.org/x/crypto/pbkdf2" @@ -23,12 +24,14 @@ import ( "github.com/xtaci/smux" ) -var ( - // VERSION is injected by buildflags - VERSION = "SELFBUILD" - // SALT is use for pbkdf2 key expansion - SALT = "kcp-go" -) +// SALT is use for pbkdf2 key expansion +const SALT = "kcp-go" + +// VERSION is injected by buildflags +var VERSION = "SELFBUILD" + +// A pool for stream copying +var xmitBuf sync.Pool type compStream struct { conn net.Conn @@ -102,7 +105,9 @@ func handleClient(p1, p2 io.ReadWriteCloser, quiet bool) { streamCopy := func(dst io.Writer, src io.Reader) chan struct{} { die := make(chan struct{}) go func() { - io.CopyBuffer(dst, src, make([]byte, 65535)) + buf := xmitBuf.Get().([]byte) + io.CopyBuffer(dst, src, buf) + xmitBuf.Put(buf) close(die) }() return die @@ -127,6 +132,10 @@ func main() { // add more log flags for debugging log.SetFlags(log.LstdFlags | log.Lshortfile) } + xmitBuf.New = func() interface{} { + return make([]byte, 65535) + } + myApp := cli.NewApp() myApp.Name = "kcptun" myApp.Usage = "server(with SMUX)"