本文介绍了ServicePoint.BindIPEndPointDelegate冻结http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的服务器上有2个IP地址。默认情况下,第一个接口的ip用于每个应用程序。但是我希望将我的c#程序绑定到另一个ip。我使用来自
此代码的代码 选择
应用程序的众多Internet连接之一 &NBSP ;.一切正常,但有一刻。默认情况下,我的简单http请求比绑定更快超过
50ms。为什么这样?我怀疑是因为我使用 BindIPEndPointDelegate
,
但我不明白为什么。
UseIP ip = new UseIP("10.8.17.245");
HttpWebRequest req = ip.CreateWebRequest(new Uri("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCUSDT"));
using(WebResponse response = req.GetResponse()) {
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
public class UseIP {
public string IP {
get;
private set;
}
public UseIP(string IP) {
this.IP = IP;
}
public HttpWebRequest CreateWebRequest(Uri uri) {
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = (servicePoint1, remoteEndPoint, retryCount) => {
IPAddress address = IPAddress.Parse(this.IP);
return new IPEndPoint(address, 0);
};
//Will cause bind to be called periodically
servicePoint.ConnectionLeaseTimeout = 0;
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(uri);
//will cause bind to be called for each request (as long as the consumer of the request doesn't set it back to true!
req.KeepAlive = false;
return req;
}
推荐答案
UseIP ip = new UseIP("10.8.17.245");
HttpWebRequest req = ip.CreateWebRequest(new Uri("https://api.binance.com/api/v1/ticker/24hr?symbol=BTCUSDT"));
using(WebResponse response = req.GetResponse()) {
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
}
public class UseIP {
public string IP {
get;
private set;
}
public UseIP(string IP) {
this.IP = IP;
}
public HttpWebRequest CreateWebRequest(Uri uri) {
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = (servicePoint1, remoteEndPoint, retryCount) => {
IPAddress address = IPAddress.Parse(this.IP);
return new IPEndPoint(address, 0);
};
//Will cause bind to be called periodically
servicePoint.ConnectionLeaseTimeout = 0;
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(uri);
//will cause bind to be called for each request (as long as the consumer of the request doesn't set it back to true!
req.KeepAlive = false;
return req;
}
这篇关于ServicePoint.BindIPEndPointDelegate冻结http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!