System.Net.WebException:无法从传输连接读取数据:连接已关闭。

System.Net.WebException: Unable to read data from the transport connection: The connection was closed.

有时下载(大)文件会出现以下错误:

System.Net.WebException: An exception occurred during a WebClient request. ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed. at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult) at System.Net.WebClient.DownloadBitsReadCallbackState(DownloadBitsState state, IAsyncResult result) --- End of inner exception stack trace ---

对我来说,这听起来像是服务器超时,但我不确定。我希望你们能给我解释一下这个问题。也许会为此提供解决方案。

下载逻辑如下所示:

            WebClient client = new WebClient();
            client.DownloadFileCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    BridgeManager.logNow("DownloadingError:\n" + e.Error.ToString());
                }

                if (e.Cancelled)
                {
                    BridgeManager.logNow("Game file download canceled!");
                }
                else
                {
                    BridgeManager.logNow("Game files downloaded!");
                    success = true;
                    downloadFinished.Set();
                }
            };




            client.DownloadFileAsync(downloadGameAddr, file);

经过一些研究并在@TetsuyaYamamoto 的帮助下,我找到了一个目前为止对我有用的解决方案。

我创建了一个从 WebClient 派生的 class 并修改了它的 WebRequest:

public class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest w = (HttpWebRequest)base.GetWebRequest(uri);
        w.ProtocolVersion = Version.Parse("1.0");
        return (WebRequest)w;
    }
}

它基本上完成了@TetsuyaYamamoto 在他的评论中推荐的内容。我只是将 WebRequest 的 Procolversion 更改为 HTTP 1.0