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

亡梦爱人 提交于 2019-12-24 08:22:13

问题


Sometimes the following error occurs by downloading a (large) file:

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 ---

For me that sounds like the server times out but I am not sure about that. I hope you guys can explain me that issue. And mabe offer a fix for that.

The download logic looks like that:

            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);

回答1:


After some research and with the help of @TetsuyaYamamoto I found a solution that works for me so far.

I created a class derived from WebClient and I modify it's 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;
    }
}

It basically does what @TetsuyaYamamoto recommended in his comment. I am just changing the Procolversion for the WebRequest to HTTP 1.0



来源:https://stackoverflow.com/questions/42516827/system-net-webexception-unable-to-read-data-from-the-transport-connection-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!