We use an HttpWebRequest object to exchange data between the server and client parts of our application. When the server's IP can't be reached or is invalid (which is something that happens, and should happen) the client either stops waiting after 3 seconds (which is the timeout I have set) or keeps waiting for up to a minute, depending on which computer it's running on! The code follows:
HttpWebRequest webRequest = null;
WebResponse webResponse = null;
webRequest = (HttpWebRequest)WebRequest.Create(serverURL);
webRequest.Timeout = 1000 * 3; //3 seconds
webRequest.ReadWriteTimeout = webRequest.Timeout;
webRequest.AllowWriteStreamBuffering = true;
//Adding headers here; code removed
webRequest.Proxy = null;
webResponse = webRequest.GetResponse();
Following advice on making the request faster which I found on this website and others, I've also set the ReadWriteTimeout property and set Proxy to null. While it correctly stops after 3 seconds on my own computer and others I've tried, on some others it won't stop until roughly 40 seconds later. I repeat that this is what happens if it tries to connect to an invalid address, such as an IP that doesn't exist inside our subnet, and that "Use the correct IP" isn't an acceptable solution (I could explain why but I think it would be off topic). If it connects to an IP that does exist, the data exc开发者_JAVA百科hange is fast like it's supposed to be.
Has anyone seen something similar?
I have no idea why this might happen, but I think you can use ping
as a workaround if you have IP (not a domain name):
Console.WriteLine(new Ping().Send(IPAddress.Parse(ipAddress)).Status);
精彩评论