我在 golang 中有这个服务器:
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(204)
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
w.Header().Set("Connection", "close")
fmt.Println(r.Close)
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":8080", nil)
}
然后我想尝试快速基准测试它如何处理这个 python 脚本的请求:
import requests
payload = "test"
while True:
r = requests.post("http://127.0.0.1:8080/test", data = payload)
r.connection.close()
多次循环后,它无法分配新的端口。我推断我的服务器没有关闭连接(或我的客户端)。
我应该如何从服务器端管理连接?
最佳答案
您的端口用完了。
由于您正在设置 w.Header().Set("Connection", "close")
,因此每个请求都将完全建立一个新连接。如果您不想用尽端口,请重新使用连接。
在您的客户端中,您将关闭整个连接池,这也将耗尽更多资源。调用 r.close()
将连接返回到池中,如果可能,它将被重用。尽管响应很小,但确保客户端使用整个响应主体仍然是一个好习惯。如果服务器无法刷新其发送缓冲区,它也将无法有效地处理连接,并且可能需要更长时间才能关闭它们。
关于go - 无法使用 golang 和 net/http 包分配请求的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30424044/