当我将HttpWebRequest发送到无法访问的Web服务器时,它会按预期超时,但只要Web服务器联机就会重新发送。 Web服务器尝试读取导致HttpListnerException且错误代码为995的请求正文。
System.Net.HttpListenerException (0x80004005): The I/O operation has been aborted because of either a thread exit or an application request.
at System.Net.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
以下是代码:
在Windows Mobile 6.5模拟器上运行的客户端.NET CF 3.5:
var request = (HttpWebRequest)WebRequest.Create("http://servername:9999/");
request.Method = "POST";
request.Timeout = 1000;
var requestBodyBytes = Encoding.UTF8.GetBytes("foobar");
request.ContentType = "text/plain";
request.ContentLength = requestBodyBytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
}
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var responseStreamReader = new StreamReader(responseStream))
{
return responseStreamReader.ReadToEnd();
}
服务器.NET Framework 4.5:
using (var listener = new HttpListener())
{
var shutdown = new ManualResetEvent(false);
var worker = new Thread(() =>
{
var signals = new WaitHandle[] { shutdown, null };
listener.Prefixes.Add("http://servername:9999/");
listener.Start();
for (;;)
{
try
{
var contextResult = listener.BeginGetContext(null, null);
signals[1] = contextResult.AsyncWaitHandle;
if (WaitHandle.WaitAny(signals) == 0)
return;
var context = listener.EndGetContext(contextResult);
var request = context.Request;
using (var requestStream = request.InputStream)
using (var requestStreamReader = new StreamReader(requestStream))
{
requestStreamReader.ReadToEnd();
}
var responseBytes = Encoding.UTF8.GetBytes(String.Format("Hello {0}", DateTime.Now));
using (var response = context.Response)
using (var responseStream = response.OutputStream)
{
response.ContentType = "text/plain";
response.ContentLength64 = responseBytes.Length;
responseStream.Write(responseBytes, 0, responseBytes.Length);
}
}
catch (Exception e)
{
// The HttpListenerException mentioned above gets thrown here.
MessageBox.Show(e.ToString());
}
}
});
worker.Start();
MessageBox.Show("Click OK to exit.");
shutdown.Set();
worker.Join();
}
要重现错误,我必须执行以下操作:
仅当我使用Compact Framework在Windows Mobile设备上运行客户端代码而在桌面上运行它时,才会出现此错误。
如何阻止Windows Mobile客户端重新发送超时请求?