无法分配请求的地址,使用golang和net/http包。

huangapple go评论93阅读模式
英文:

Cannot assign requested address with golang and net/http packages

问题

我有一个用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()

经过多次循环后,它无法分配新的端口。我推断是我的服务器没有关闭连接(或者我的客户端)。

我应该如何在服务器端管理连接?

英文:

I have this server in 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)
}

Then I wanted to try to quickly benchmark how it can handle requests whit this python script:

import requests

payload = "test"

while True:
    r = requests.post("http://127.0.0.1:8080/test", data = payload)
    r.connection.close()

After multiple loops it cannot assign new ports. I deduce that my server doesn't close connection (or my client).

How should I manage connection from server side?

答案1

得分: 1

你的端口即将用尽。

由于你在每个请求中设置了w.Header().Set("Connection", "close"),每个请求都会使用一个全新的连接。如果你不想用尽端口,可以重用连接。

在你的客户端中,你关闭了整个连接池,这也会消耗更多的资源。调用r.close()将连接返回给连接池,如果可能的话,它将被重用。即使响应很小,确保客户端消耗完整个响应体仍然是一个好的做法。如果服务器无法刷新其发送缓冲区,它也无法高效处理连接,并且关闭连接可能需要更长的时间。

英文:

You're running out of ports.

Since you're setting w.Header().Set("Connection", "close") each request is going to take a new connection entirely. If you don't want to use up ports, re-use the connections.

In your client, you're closing entire connection pool, which also will use up more resources. Call r.close() to return the connection to the pool and it will be reused if possible. Even though the response is small, it's still good practice to ensure the client consumes the entire response body. If the server can't flush its send buffers, it won't be able to efficiently handle the connections either, and it may take longer to close them.

huangapple
  • 本文由 发表于 2015年5月24日 21:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/30424044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定