C#利用 HttpWebRequest 类发送post请求,出现“套接字(协议/网络地址/端口)只允许使用一次”问题
2024-10-10 04:08:27
声明:问题虽然已经被解决,但是并没有明白具体原理,欢迎大佬补充。
最近网站出现一个问题,在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();
}
到此, “套接字(协议/网络地址/端口)只允许使用一次” 这个问题已经不会再出现了。。。
最新文章
- 为C#自定义控件添加自定义事件
- 1.一起来学hibernate之hibernate简介
- Linux 输出文件列数,拼接文件
- C#<;热血传奇>;服务端源代码再次给力更新
- 【HDOJ】3285 Convex Hull of Lattice Points
- Performing a full database disaster recovery with RMAN
- Make Hadoop 1.2.1 run, my first try
- python导出zabbix数据并发邮件脚本
- git合并常见冲突
- vue 学习小记
- TensorFlow——循环神经网络基本结构
- Chemical table CFR500 div2D(并查集)
- php年会抽奖
- 白话RPC
- 理解 neutron(15):Neutron Linux Bridge + VLAN/VXLAN 虚拟网络
- Redis数据类型之SDS简单动态字符串
- Layabox 3D游戏开发学习笔记---射线检测,鼠标控制物体运动
- SpringMvc 400 Bad Request解决方法
- Ubuntu16.04安装视觉SLAM环境(OpenCV)
- 洛谷P3960 列队(动态开节点线段树)
热门文章
- vue+原生JavaScript实现slideDown与slideUp[简单思路]
- 安装odoo小程序商城模块报错 KeyError: u&#39;oejia_weshop&#39;
- Android View的重绘ViewRootImpl的setView方法
- 工具资源系列之给虚拟机装个windows
- VS打开项目或解决方案卡死,一直处于未响应状态。
- HTML 、XHTML、H5的区别:
- spark2.4 分布式安装
- oracle 当前年到指定年的年度范围求取
- c文件操作整理
- 网络流 E - Escape HDU - 3605