gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:16:27 26 4
gpt4 key购买 nike

我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com