我编写了一个应用程序,该应用程序可以部分地从特定的Web服务下载文件。该代码利用HttpClient进行调用。问题是,有时我会收到带有以下异常消息的失败请求:
无法从传输连接读取数据:连接已关闭。
我确实浏览了这些博客文章,其中作者不得不将协议版本还原为1.0,禁用保持活动状态,并限制服务点连接的数量:
我遵循了这些指示,尽我所能,但仍然出现错误。我还确保保持HttpClient的单个实例不变(遵循Singleton原理)。
有趣的是,在运行Fiddler时,我还没有收到错误消息,这使我认为在客户端可以执行某些操作,因为Fiddler似乎正在执行某些操作以保持连接有效(尽管问题是非常零星,这可能是个红色鲱鱼)。
还有一些注意事项:
该错误总是在下载过程中发生(从不发起请求)。
该文件将继续下载直到失败为止(首先没有扩展的暂停或延迟)。
-更新-
错误发生在以下行:
responseTask.Wait(cancellationTokenSource.Token);
Run Code Online (Sandbox Code Playgroud)
以下是完全例外:
System.AggregateException occurred HResult=-2146233088 Message=One
or more errors occurred. Source=mscorlib StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Form1.StartDownload() in c:\Projects\Visual Studio 2012\Demo\Demo\Form1.cs:line 88 InnerException:
System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Error while copying content to a stream.
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.Handlers.ProgressStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
InnerException:
Run Code Online (Sandbox Code Playgroud)
-更新#2--
我以为我会尝试将完成选项从“内容已读”更改为“标题已读”。即使在不同的位置(TODO注释所在的位置,读取内容流),该操作也因相同的异常而失败。
-更新#3--
我可以确认Web服务(由IIS托管)正在中止连接(IIS日志显示的Win32状态代码为1236-ERROR_CONNECTION_ABORTED)。为了尝试缩小范围,将MinFileBytesPerSec配置数据库属性设置为零(如果客户端停止暂时拉下数据,则为零),并且连接仍在中止。我仔细检查了所有的超时和缓冲区大小,但没有用。此刻在稀薄的空气中挣扎。任何想法,将不胜感激。
客户端设置:
private void SetupClient()
{
// In case we're taxing the web server, limit the number
// connections we're allowed to make to one.
ServicePointManager.DefaultConnectionLimit = 1;
// Set up the progress handler so that we can keep track of the download progress.
_progressHandler = new ProgressMessageHandler();
_progressHandler.HttpReceiveProgress += ProgressHandler_HttpReceiveProgress;
// Create our HttpClient.
_client = HttpClientFactory.Create(_progressHandler);
_client.BaseAddress = new Uri("http://localhost");
_client.Timeout = TimeSpan.FromMinutes(30);
_client.DefaultRequestHeaders.TransferEncodingChunked = true;
}
Run Code Online (Sandbox Code Playgroud)
下载逻辑:
private void StartDownload()
{
// Create the request.
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Download"))
{
// Revert the protocol version and turn off keep alive in accordance with:
// http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/
// http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/
request.Version = new Version("1.0");
request.Headers.Add("Keep-Alive", "false");
// Set the cancellation token's timeout to 30 minutes.
int timeoutInMilliseconds = 30 * 60 * 1000;
using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeoutInMilliseconds))
{
// Making sure that the message isn't "complete" until everything is read in so we can cancel it at anytime.
Task<HttpResponseMessage> responseTask = _client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
responseTask.Wait(cancellationTokenSource.Token);
using (HttpResponseMessage response = responseTask.Result)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception("Request failed!");
}
Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
using (Stream contentStream = streamTask.Result)
{
// TODO: Save to disk.
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2256 次 |
| 最近记录: |