From f1102c0062417f8c899bd1067383e7530c3e483f Mon Sep 17 00:00:00 2001 From: "Matthew B. Gray" Date: Fri, 20 Oct 2017 14:13:34 +1300 Subject: [PATCH] Add rate option so sender can restrict outgoing speed closes #7 --- connect.go | 10 +++++++++- main.go | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/connect.go b/connect.go index 3789945..0f64567 100644 --- a/connect.go +++ b/connect.go @@ -28,6 +28,7 @@ type Connection struct { Debug bool DontEncrypt bool bars []*uiprogress.Bar + rate int } type FileMetaData struct { @@ -46,6 +47,7 @@ func NewConnection(flags *Flags) *Connection { c.Server = flags.Server c.Code = flags.Code c.NumberOfConnections = flags.NumberOfConnections + c.rate = flags.Rate if len(flags.File) > 0 { c.File.Name = flags.File c.IsSender = true @@ -382,7 +384,13 @@ func (c *Connection) sendFile(id int, connection net.Conn) { if !c.Debug { c.bars[id] = uiprogress.AddBar(chunksPerWorker).AppendCompleted().PrependElapsed() } - for { + + bufferSizeInKilobytes := BUFFERSIZE / 1024 + rate := float64(c.rate) / float64(c.NumberOfConnections*bufferSizeInKilobytes) + throttle := time.NewTicker(time.Second / time.Duration(rate)) + defer throttle.Stop() + + for range throttle.C { _, err = file.Read(sendBuffer) if err == io.EOF { //End of file reached, break out of for loop diff --git a/main.go b/main.go index 6d47f75..178d1b2 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,8 @@ import ( const BUFFERSIZE = 1024 +var oneGigabytePerSecond = 1000000 // expressed as kbps + type Flags struct { Relay bool Debug bool @@ -17,6 +19,7 @@ type Flags struct { Server string File string Code string + Rate int NumberOfConnections int } @@ -37,6 +40,7 @@ croc version `+version+` flag.StringVar(&flags.Server, "server", "cowyo.com", "address of relay server") flag.StringVar(&flags.File, "send", "", "file to send") flag.StringVar(&flags.Code, "code", "", "use your own code phrase") + flag.IntVar(&flags.Rate, "rate", oneGigabytePerSecond, "throttle down to speed in kbps") flag.BoolVar(&flags.DontEncrypt, "no-encrypt", false, "turn off encryption") flag.IntVar(&flags.NumberOfConnections, "threads", 4, "number of threads to use") flag.Parse()