doubushi0031 2017-12-01 05:26
浏览 140

Go http.Get何时重用tcp连接?

in GO net/http Response Body annotation says:

It is the caller's responsibility to close Body. The default HTTP client's Transport does not attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections ("keep-alive") unless the Body is read to completion and is closed.

It's mean: if I use http.Get and don't call resp.Body.Close() then it will not resue HTTP/1.0 or HTTP/1.1 TCP connections ("keep-alive") yeah?

so I write some code:

package main

import ( "time" "fmt" "io/ioutil" "net/http" )

func main() { resp, err := http.Get("http://127.0.0.1:8588")

if err != nil {
    panic(err)
}
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
    panic(err)
}

resp2, err := http.Get("http://127.0.0.1:8588")

if err != nil {
    panic(err)
}
_, err = ioutil.ReadAll(resp2.Body)
if err != nil {
    panic(err)
}

fmt.Println("before time sleep")
time.Sleep(time.Second * 35)

}

and I only see ONE tcp connection build in wireshark, why? I don't close res.Body so the http client should't be reuse the tcp connection.
  • 写回答

2条回答 默认 最新

  • doushenyi9104 2017-12-01 05:56
    关注

    You have read it till the end in first occurence of line:

    _, err = ioutil.ReadAll(resp.Body)
    

    So the connection is ready to be resused. Try not to read and run again.

    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?