最近一个 golang 写的 http.clIEnt 的,获取远程服务器数据,有时候会报错,尤其在数量很大的时候,老是收到 Connection reset by peer 这样的 提醒,都有点想用重试机制
百度,goolge 了一翻后,说的是 它会阻止连接被重用,可以有效的防止这个问题,也就是http的短连接
1.在客户端关闭 http 连接
func main() { req,err := http.NewRequest("GET","http://localhost",nil ) if err != nil { log.Errorf("") } req.Close = true resp,err := http.ClIEnt.Do(req) ...}
在头部设置连接状态为关闭
func main() { req,nil ) if err != nil { log.Errorf("") } req.header.Add("Connection","close") resp,err := http.ClIEnt.Do(req) ...}使用
Transport
取消 http利用连接 func main() { tr := http.Transport{disableKeepAlives: true} clIEnt := http.ClIEnt{Transport: &tr} resp,err := clIEnt.Get("https://golang.Google.cn/") if resp != nil { defer resp.Body.Close() } checkerror(err) fmt.Println(resp.StatusCode) // 200 body,err := IoUtil.ReadAll(resp.Body) checkerror(err) fmt.Println(len(string(body)))}
服务器端设置短连接
func main(){ server := &http.Server{ Handler:handle,ReadTimeout: 20 * time.Second,WriteTimeout: 20 * time.Second,} Listen,err := net.Listen("tcp4",s.addr) if err != nil { logger.Errorf("Failed to Listen,err:%s",err.Error()) panic(err) } server.SetKeepAlivesEnabled(false) err = server.Serve(Listen)}
参考 了
https://blog.csdn.net/cyberspecter/article/details/83308348
https://my.oschina.net/shou1156226/blog/808613 总结以上是内存溢出为你收集整理的golang http.client 遇到了 Connection reset by peer 问题全部内容,希望文章能够帮你解决golang http.client 遇到了 Connection reset by peer 问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)