Search code examples
goports

Why does the client hang when the local port is specified?


This is related to a homework assignment that must be submitted in Java. The program works as expected printing the contents of server.go to the terminal. Why does the client hang for 30 seconds after two or more sequential runs?

The delay only occurs when the client port is specified (related to the assignment).

// server.go
package main

import (
    "log"
    "net/http"
)

func main() {
    log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("."))))
}

I'd expect the delay to be a timeout waiting for the connection to close if it were not for defer conn.Close() and the client running only after the previous client returned.

// client.go
package main

import (
    "fmt"
    "io"
    "log"
    "net"
    "os"
)

func main() {
    d := net.Dialer{
        LocalAddr: &net.TCPAddr{
            Port: 8081,
        },
    }

    // Dial the server from client port 8081 to server port 8080
    conn, err := d.Dial("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    // Request the resource and log the response
    fmt.Fprint(conn, "GET /server.go HTTP/1.0\r\n\r\n")
    io.Copy(os.Stdout, conn)
}

Output of netstat during a delay:

$ netstat -anp tcp | grep "8080\|8081"
tcp4       0      0  127.0.0.1.8081         127.0.0.1.8080         SYN_SENT   
tcp46      0      0  *.8080                 *.*                    LISTEN    

Solution

  • I can reproduce that error. AFAICS it has to do with the TCP closing sequence, see this - http://www.tcpipguide.com/free/t_TCPConnectionTermination-4.htm

    On OS X you can mess with the tcp MSL like this

    sudo sysctl net.inet.tcp.msl=100
    

    So a modified client

    // client.go
    package main
    
    import (
        "fmt"
        "io"
        "log"
        "net"
        "os"
        "time"
    )
    
    func check() {
        d := net.Dialer{
            LocalAddr: &net.TCPAddr{
                Port: 8081,
            },
        }
    
        // Dial the server from client port 8081 to server port 8080
        conn, err := d.Dial("tcp", ":8080")
        if err != nil {
            log.Fatal(err)
        }
    
        // Request the resource and log the response
        fmt.Fprint(conn, "GET /server.go HTTP/1.0\r\n\r\n")
        io.Copy(os.Stdout, conn)
        conn.Close()
    }
    
    // sudo sysctl net.inet.tcp.msl=100
    func main() {
    
        count := 0
        for {
            fmt.Printf("Try num %d\n", count)
            count++
            check()
            time.Sleep(200 * time.Millisecond)
        }
    }
    

    See https://en.wikipedia.org/wiki/Maximum_segment_lifetime