HttpWebRequest在启用多个网络适配器时超时

时间:2010-03-23 11:27:39

标签: c# networking httpwebrequest

在我的Win7 PC上,我有几个用于VMWare服务器的虚拟网络适配器。 当我启用这些适配器时,我的HttpWebRequest超时。我真的要告诉它要绑定哪个适配器吗?

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.AbsoluteUri + "etc.txt");
            request.Timeout = 2000;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }

更新

我猜这是一个常见的问题。有没有人有一个标准的方法来处理这个?我不能真正提示用户界面,因为他们是非技术人员。 Rohit的答案是展示如何设置ServicePoint的良好开端。

2 个答案:

答案 0 :(得分:4)

Tim,如果你看到超时,那是因为你的新适配器有URL的路由,而且它们没有到达目的地。

public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount);

您可以将其用作

private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint,IPEndPoint remoteEndPoint, int retryCount)
{
    if(retryCount < 3)
        return new IPEndPoint(IPAddress.Parse("192.168.10.60"), 0); 
    else
        return new IPEndPoint(IPAddress.Any, 0);
}

和...

 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
 req.ServicePoint.BindIPEndPointDelegate =  new BindIPEndPoint(BindIPEndPointCallback);

有关详细信息,请参阅http://www.netbrick.net/blog/PermaLink,guid,b9c255d9-74b4-45ab-8fd0-c9a04784655a.aspx

答案 1 :(得分:0)

来自Rohits的回答。这可以很好地尝试所有的适配器吗?

    private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
    {
        List<IPEndPoint> endPoints = new List<IPEndPoint>();

        foreach (NetworkInterface netinface in NetworkInterface.GetAllNetworkInterfaces())
        {
            foreach (IPAddressInformation unicast in netinface.GetIPProperties().UnicastAddresses)
            {
                if(unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    endPoints.Add(new IPEndPoint(unicast.Address, 80));
            }
        }

        if (retryCount > endPoints.Count - 1)
            return new IPEndPoint(IPAddress.Any, 80);
        else
            return endPoints[retryCount];
    }