Golang"Connection reset"&"EOF"问题

栏目: Go · 发布时间: 7年前

内容简介:【场景】在调用微信生成小程序二维码生成接口的时候,使用golang默认的http client发送请求。代码如下:

【场景】

在调用微信生成小程序二维码生成接口的时候,使用golang默认的http client发送请求。

代码如下:

req, err := http.NewRequest(method, url, body)

iferr !=nil{

    return nil, err

}

resp, err := http.DefaultClient.Do(req)

if err !=nil{

    return nil, err

}

defer resp.Body.Close()

b, err := ioutil.ReadAll(resp.Body)

if err !=nil{

return nil, err

}

当并发量大的时候就会出现大量的错误

ERROR 10108 socket.cpp:985 0x7fffe81426e0 recvmsg(62, 1): (104, "Connection reset by peer")

WARN 10108 server.cpp:467  0x7fffe80abd60-2 Unexpected SocketException

【原因】

在解决问题之前需要了解关于 go 是如何实现connection的一些背景小知识:有两个协程,一个用于读,一个用于写(就是readLoop和writeLoop)。在大多数情况下,readLoop会检测socket是否关闭,并适时关闭connection。如果一个新请求在readLoop检测到关闭之前就到来了,那么就会产生EOF错误并中断执行,而不是去关闭前一个请求。

我执行时建立一个新的连接并发送keep-alive,服务器收到后将我的keep-alive发回并立即关闭了连接。当这段程序执行后退出,再次执行时服务器已经关闭了连接,而我的客户端却仍在重用之前建立的连接,所以提示连接被重置;如果我不退出程序而使用for循环多次发送时,旧连接未及时关闭,新连接却到来,EOF的错误也就产生了。

【解决】

req.Close = true

它会阻止连接被重用,可以有效的防止这个问题,也就是Http的短连接。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to the Analysis of Algorithms

An Introduction to the Analysis of Algorithms

Robert Sedgewick、Philippe Flajolet / Addison-Wesley Professional / 1995-12-10 / CAD 67.99

This book is a thorough overview of the primary techniques and models used in the mathematical analysis of algorithms. The first half of the book draws upon classical mathematical material from discre......一起来看看 《An Introduction to the Analysis of Algorithms》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具