下面是一个简单的Go http(tcp)连接测试脚本
func main() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
var wg sync.WaitGroup
for i := 0; i < 2000; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
resp, err := http.Get(ts.URL)
if err != nil {
panic(err)
}
greeting, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
panic(err)
}
fmt.Printf("%s", i, greeting)
}(i)
}
wg.Wait()
}
如果我在Ubuntu中运行这个程序,我会得到:
panic: Get http://127.0.0.1:33202: dial tcp 127.0.0.1:33202: too many open files
个
其他帖子说要确保Close
%的连接,我在这里做这一切.
如何在一台服务器上运行数百万个tcp连接Goroutine?
谢谢,