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.
This commit is contained in:
Peter J. Holzer 2020-12-20 15:23:59 +01:00 committed by Peter J. Holzer
parent 70d3daeccb
commit 3d9133f93f
1 changed files with 12 additions and 8 deletions

View File

@ -2,8 +2,8 @@ package main
import ( import (
"encoding/binary" "encoding/binary"
"gopkg.in/alecthomas/kingpin.v2"
"fmt" "fmt"
"gopkg.in/alecthomas/kingpin.v2"
"log" "log"
"net" "net"
"os" "os"
@ -16,7 +16,7 @@ var (
server = app.Command("server", "Run as server") server = app.Command("server", "Run as server")
listenAddress = server.Arg("address", "Address:port to listen on").String() 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() serverAddress = client.Arg("address", "Address:port to connect to").String()
) )
@ -63,12 +63,16 @@ func tcpdelayClient() {
o := 0 o := 0
buffer := make([]byte, 1024) buffer := make([]byte, 1024)
for { for {
n, err := conn.Read(buffer) n := 0
if err != nil { for n < len(buffer) {
log.Fatal("Cannot read from ", *serverAddress, err) nr, err := conn.Read(buffer[n:])
} if err != nil {
if n != len(buffer) { log.Fatal("Cannot read from ", *serverAddress, err.Error())
log.Fatal("Read ", n, " bytes intead of ", len(buffer)) }
if nr <= 0 {
log.Fatal("Read ", n, " bytes intead of ", len(buffer))
}
n += nr
} }
tr := time.Now().UnixNano() tr := time.Now().UnixNano()
if string(buffer[0:8]) != "tcpdelay" { if string(buffer[0:8]) != "tcpdelay" {