networking - 使用 ResponseWriter.Write 在 Go 中连接 250 次后出现 "localhost: no such host"

标签 networking go

我有以下 http 客户端/服务器代码:

服务器

func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Req: ", r.URL)
        w.Write([]byte("OK")) // <== PROBLEMATIC LINE
        // w.WriteHeader(200) // Works as expected
    })

    log.Fatal(http.ListenAndServe(":5008", nil))
}

客户端

func main() {

    client := &http.Client{}

    for i := 0; i < 500; i++ {
        url := fmt.Sprintf("http://localhost:5008/%02d", i)
        req, _ := http.NewRequest("GET", url, nil)
        _, err := client.Do(req)

        if err != nil {
            fmt.Println("error: ", err)
        } else {
            fmt.Println("success: ", i)
        }

        time.Sleep(10 * time.Millisecond)
    }
}

当我在服务器上运行上面的客户端时,在 250 个连接后,我从 client.Do 收到以下错误:
error: Get http://localhost:5008/250: dial tcp: lookup localhost: no such host 没有更多的连接会成功。

如果我将服务器中的行从 w.Write([]byte("OK")) ==> w.WriteHeader(200) 更改为然后对连接数量没有限制,并且按预期工作。

我在这里错过了什么?

最佳答案

你没有关闭 body 。当您从服务器进行任何写入时,连接将保持打开状态,因为尚未读取响应。当你只是 WriteHeader 时,响应就完成了,连接可以被重用或关闭。

老实说,我不知道为什么保持打开的连接会导致域查找失败。基于 250 非常接近整数 256 这一事实,我猜想您遇到的操作系统存在人为限制。也许允许的最大 FD 是 256?看起来很低,但它可以说明问题。

func main() {
    client := &http.Client{}

    for i := 0; i < 500; i++ {
        url := fmt.Sprintf("http://localhost:5008/%02d", i)
        req, _ := http.NewRequest("GET", url, nil)
        resp, err := client.Do(req)

        if err != nil {
            fmt.Println("error: ", err)
        } else {
            fmt.Println("success: ", i)
        }
        resp.Body.Close()

        time.Sleep(10 * time.Millisecond)
    }
}

关于networking - 使用 ResponseWriter.Write 在 Go 中连接 250 次后出现 "localhost: no such host",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26228163/

相关文章:

c++ - 使用 unix 套接字的同步 boost asio 中的延迟/延迟

linux - 如何在两个接口(interface)之间建立 Telnet 连接隧道?

google-app-engine - datastore.Get 使用祖父 key

go - 有没有办法更新 go 包并忽略错误?

go - 从GetWindowThreadProcessId调用返回的PID与TaskManager的PID不匹配

windows - 如何判断网络适配器在 Windows 上是否可移动

linux - 当我尝试通过原始套接字连接 TCP 服务器时,为什么它不回复我的 syn 数据包?

sockets - 如何防止接收套接字永远阻塞以防万一它没有接收到任何数据?

json - Golang 使用类型

xml - 高语 : Refactoring xml tag definition in struct