tcp通过对等方重置连接

时间:2016-08-12 06:49:55

标签: go concurrency

我在启动90000多个go例程以通过POST向同一服务器执行http请求时遇到问题,服务器和客户端都在本地,一些请求成功执行,其中一些请求给我这个响应读取:由同行重置连接

请注意我在提供的示例中发布了少量数据 但实际上我使用protobuf发送大量数据。

这是服务器https://play.golang.org/p/r1-rYNuAos

package main

import (
    "net/http"
    "log"
    "encoding/json"
)

var port string

type problem struct{
}

func main() {
    p := &problem{}
    p.server(":9090")
}

func (self *problem)server(port string) {
    s := &http.Server{
        Addr:           port,
        Handler:        self,
    }
    log.Println("Server started")
    // Should be last line as it is a blocking.
    log.Fatal(s.ListenAndServe())
}

func (self *problem) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    if err := json.NewEncoder(w).Encode(map[string]interface{}{"created": true}); err != nil {
        log.Fatal(err.Error())
    }
}

这是客户https://play.golang.org/p/Xx5qQoqrYm

package main

import (
    "net/http"
    "bytes"
    "io/ioutil"
    "log"
    "fmt"
)

type problem struct{
}

func main() {
    p := &problem{}
    p.client(":9090")
}

func (self *problem)client(port string) {
    var k int

    for k=0;k<90000;k++ {

        go func(){

            nativeRequest, err := http.NewRequest(
                "POST",
                "http://127.0.0.1" + port + "/",
                bytes.NewBuffer([]byte(`testing`)),
            )

            nativeRequest.Close = true

            if err != nil {
                fmt.Println(err.Error())
            }

            client := &http.Transport{
            }
            nativeResponse, err := client.RoundTrip(nativeRequest)

            if err != nil {
                log.Println(err.Error())
            }

            if nativeResponse != nil {
                defer nativeResponse.Body.Close()

                if err != nil {
                        fmt.Println(err.Error())
                }

                body, err := ioutil.ReadAll(nativeResponse.Body)

                if err != nil {
                        fmt.Println(err.Error())
                }

                fmt.Println(string(body))
            }
        }()
    }
}

0 个答案:

没有答案