An existing connection was forcibly closed by the remote host

后端 未结 12 2025
说谎
说谎 2020-11-22 09:26

I am working with a commercial application which is throwing a SocketException with the message,

An existing connection was forcibly closed by the rem

12条回答
  •  遥遥无期
    2020-11-22 09:45

    For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

    using (var remoteStream = await response.Content.ReadAsStreamAsync())
    using (var content = File.Create(DownloadPath))
    {
        var buffer = new byte[1024];
        int read;
    
        while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
        {
            await content.WriteAsync(buffer, 0, read);
            await content.FlushAsync();
        }
    }
    

    After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:

    using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
    using (FileStream content = File.Create(DownloadPath))
    {
        await remoteStream.CopyToAsync(content);
    }
    

    CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

    It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

    "Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."

    The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

    In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

提交回复
热议问题