dongni8969
2015-01-25 21:32
浏览 34
已采纳

指定本地端口后,为什么客户端挂起?

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

")
    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    
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtbonklcs575884485 2015-06-22 16:42
    已采纳

    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
    
    ")
        io.Copy(os.Stdout, conn)
        conn.Close()
    }
    
    // sudo sysctl net.inet.tcp.msl=100
    func main() {
    
        count := 0
        for {
            fmt.Printf("Try num %d
    ", count)
            count++
            check()
            time.Sleep(200 * time.Millisecond)
        }
    }
    

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

    打赏 评论

相关推荐 更多相似问题