声明:问题虽然已经被解决,但是并没有明白具体原理,欢迎大佬补充。

最近网站出现一个问题,在C#里面使用  HttpWebRequest 类去发送post请求,偶尔 会出现 “套接字(协议/网络地址/端口)只允许使用一次” 的异常,很明显应该是端口被占用。

原因排查:

1、网上说最多就是其他程序占用端口:因为已经上线,并且有时候可以正常运行,因此排除其他程序占用端口的可能,而且我网站用的就是80端口。

2、第二个可能原因就是接口性能较差,占用较长处理时间:我 给post的目标接口(因为接口也是本身网站提供的,因此可以进行监控) 加上时间日志,发现处理时长都在 30ms -50 ms 左右,而且网站访问量并不是很大,因此这个处理速度还是非常快的,按理说不应该出现端口占用情况。

我们现在来看一下post代码 ,如下:

private string sendHttpWebRequest(bool isPost, string sendData, string requestURL)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(sendData);
// 制备web请求
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestURL);
if (isPost)
{
myRequest.Method = "POST";
}
else
{
myRequest.Method = "GET";
}
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
if (isPost)
{
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, , data.Length);
newStream.Close();
}
}

最后 我发现上面的代码并没有接收返回,是因为这个接口本身设计的问题,接口只是为了通知,并不关心返回结果(当然这本身不是一个好的设计) 。

但是经过测试,问题就出在没有接收返回上,加上接收返回的代码以后, “套接字(协议/网络地址/端口)只允许使用一次” 的异常就消失 了!

最后post代码如下:

private string sendHttpWebRequest(bool isPost, string sendData, string requestURL)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(sendData);
// 制备web请求
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestURL);
if (isPost)
{
myRequest.Method = "POST";
}
else
{
myRequest.Method = "GET";
}
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
if (isPost)
{
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, , data.Length);
newStream.Close();
}
   //获取响应
  HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
  StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
   return reader.ReadToEnd();
}

到此, “套接字(协议/网络地址/端口)只允许使用一次”  这个问题已经不会再出现了。。。

最新文章

  1. 为C#自定义控件添加自定义事件
  2. 1.一起来学hibernate之hibernate简介
  3. Linux 输出文件列数,拼接文件
  4. C#<热血传奇>服务端源代码再次给力更新
  5. 【HDOJ】3285 Convex Hull of Lattice Points
  6. Performing a full database disaster recovery with RMAN
  7. Make Hadoop 1.2.1 run, my first try
  8. python导出zabbix数据并发邮件脚本
  9. git合并常见冲突
  10. vue 学习小记
  11. TensorFlow——循环神经网络基本结构
  12. Chemical table CFR500 div2D(并查集)
  13. php年会抽奖
  14. 白话RPC
  15. 理解 neutron(15):Neutron Linux Bridge + VLAN/VXLAN 虚拟网络
  16. Redis数据类型之SDS简单动态字符串
  17. Layabox 3D游戏开发学习笔记---射线检测,鼠标控制物体运动
  18. SpringMvc 400 Bad Request解决方法
  19. Ubuntu16.04安装视觉SLAM环境(OpenCV)
  20. 洛谷P3960 列队(动态开节点线段树)

热门文章

  1. vue+原生JavaScript实现slideDown与slideUp[简单思路]
  2. 安装odoo小程序商城模块报错 KeyError: u'oejia_weshop'
  3. Android View的重绘ViewRootImpl的setView方法
  4. 工具资源系列之给虚拟机装个windows
  5. VS打开项目或解决方案卡死,一直处于未响应状态。
  6. HTML 、XHTML、H5的区别:
  7. spark2.4 分布式安装
  8. oracle 当前年到指定年的年度范围求取
  9. c文件操作整理
  10. 网络流 E - Escape HDU - 3605