Golang - Socket Read Operation is taking long time

Viewed 40

I'm trying to read the response from a socket using the tcp connection type and net package in go.

func main() {

    start := time.Now()

    con, _ := net.Dial("tcp", "prodserver:6778")

    defer con.Close()

    b := make([]byte, 0, 512)
    k := 0
    for {
        if len(b) == cap(b) {
            b = append(b, 0)[:len(b)]
        }

        readStart := time.Now()
        n, err := con.Read(b[len(b):cap(b)])
        readEnd := time.Since(readStart)
        
        fmt.Print("Start Iteraton #" + strconv.Itoa(k) + " ")
        fmt.Print(readEnd)
        fmt.Println(" End Iteraton #" + strconv.Itoa(k) + " byte size: " + strconv.Itoa(len(b)) + " ")

        b = b[:len(b)+n]
        if err != nil {
            if err == io.EOF {
                err = nil
            }
            // return b, err
            break
        }
        k++
    }
}

So I have tried calculate the duration taken for each read and printed to the console. And the results were interesting, all the read operations were very fast it took around a micro or milli seconds to complete except for the last read, it took around 1 minute.

Output:

Start Iteraton #0 551.32278ms End Iteraton #0 byte size: 0

Start Iteraton #1 11.577µs End Iteraton #1 byte size: 512

Start Iteraton #2 10.333µs End Iteraton #2 byte size: 896

Start Iteraton #3 5.204µs End Iteraton #3 byte size: 1408

Start Iteraton #4 6.605µs End Iteraton #4 byte size: 2048

Start Iteraton #5 6.452µs End Iteraton #5 byte size: 3072

//

// so on for the rest of iteration the time taken was very similar to above

//

Start Iteraton #238 37.747µs End Iteraton #238 byte size: 340285

Start Iteraton #239 23.235µs End Iteraton #239 byte size: 341630

Start Iteraton #240 58.041µs End Iteraton #240 byte size: 342975

Start Iteraton #241 34.192µs End Iteraton #241 byte size: 344320

Start Iteraton #242 101.094µs End Iteraton #242 byte size: 345665

Start Iteraton #243 1m0.307097139s End Iteraton #243 byte size: 346430

Any idea on why the last read operation is taking long time to complete? Is there any timeout we need to set.

0 Answers
Related