From 3d9133f93fbe267be567506ae16ab63b58b0931c Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Sun, 20 Dec 2020 15:23:59 +0100 Subject: [PATCH] Reassemble partial packets on the client The sender's network stack assembles tcp packets without regard for write boundaries, so the receiver has to be prepared for partial reads. --- tcpdelay.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/tcpdelay.go b/tcpdelay.go index 3f7a952..3087a37 100644 --- a/tcpdelay.go +++ b/tcpdelay.go @@ -2,8 +2,8 @@ package main import ( "encoding/binary" - "gopkg.in/alecthomas/kingpin.v2" "fmt" + "gopkg.in/alecthomas/kingpin.v2" "log" "net" "os" @@ -16,7 +16,7 @@ var ( server = app.Command("server", "Run as server") listenAddress = server.Arg("address", "Address:port to listen on").String() - client = app.Command("client", "Request measurement") + client = app.Command("client", "Request measurement") serverAddress = client.Arg("address", "Address:port to connect to").String() ) @@ -63,12 +63,16 @@ func tcpdelayClient() { o := 0 buffer := make([]byte, 1024) for { - n, err := conn.Read(buffer) - if err != nil { - log.Fatal("Cannot read from ", *serverAddress, err) - } - if n != len(buffer) { - log.Fatal("Read ", n, " bytes intead of ", len(buffer)) + n := 0 + for n < len(buffer) { + nr, err := conn.Read(buffer[n:]) + if err != nil { + log.Fatal("Cannot read from ", *serverAddress, err.Error()) + } + if nr <= 0 { + log.Fatal("Read ", n, " bytes intead of ", len(buffer)) + } + n += nr } tr := time.Now().UnixNano() if string(buffer[0:8]) != "tcpdelay" {