无法从传输连接读取数据:远程主机强制关闭现有连接

时间:2012-01-13 18:16:21

标签: c# http iis httpwebrequest

当我通过HTTP传输大约50Mb的文件有时时,我收到此错误:

无法从传输连接读取数据:远程主机强行关闭现有连接。

首先,我在http://stackoverflow.com下找不到任何解决方案。

我有什么需要改进/改变的线索?

的app.config:

 <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_MyDomainServicesoap" closeTimeout="00:03:00" openTimeout="00:04:00" receiveTimeout="00:10:00" sendTimeout="00:05:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="50000000" maxBufferPoolSize="50000000" maxReceivedMessageSize="50000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="64" maxStringContentLength="16384" maxArrayLength="32768" maxBytesPerRead="8192" maxNameTableCharCount="16384"/>
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default"/>
          </security>
        </binding>
        <binding name="BasicHttpBinding_MyAuthenticationDomainServicesoap" closeTimeout="00:03:00" openTimeout="00:04:00" receiveTimeout="00:10:00" sendTimeout="00:05:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="50000000" maxBufferPoolSize="50000000" maxReceivedMessageSize="50000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="64" maxStringContentLength="16384" maxArrayLength="32768" maxBytesPerRead="8192" maxNameTableCharCount="16384"/>
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>

代码:

private void FinishWebRequest(IAsyncResult result)
        {
            // Assign values to these objects here so that they can be referenced in the finally block
            Stream remoteStream = null;
            Stream localStream = null;
            WebResponse response = null;

            try
            {
                response = request.EndGetResponse(result);

              if (response != null)
                {
                    // Once the WebResponse object has been retrieved, get the stream object associated with the response's data
                    remoteStream = response.GetResponseStream();

                    // Create the local file
                    string pathToSaveFile = Path.Combine(FileManager.GetFolderContent(), FileView.Filename);
                    localStream = File.Create(pathToSaveFile);

                    WinAPI.SYSTEM_INFO sysinfo = new WinAPI.SYSTEM_INFO();
                    WinAPI.GetSystemInfo(ref sysinfo);

                    // Allocate a buffer 
                    byte[] buffer = new byte[int.Parse(sysinfo.dwPageSize.ToString())];     
                    int bytesRead;

                    // Simple do/while loop to read from stream until no bytes are returned
                    do
                    {
                        // Read data (up to 1k) from the stream
                        bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                        // Write the data to the local file
                        localStream.Write(buffer, 0, bytesRead);

                        // Increment total bytes processed
                        BytesProcessed += bytesRead;
                    } while (bytesRead > 0);

                    FileView.Downloaded = DateTime.Now;

                    if (BytesProcessed > 0)
                    {
                        FileView.IsSuccess = true;
                        FileView.IsDownloading = false;
                    }
                    else
                    {
                        FileView.IsSuccess = false;
                        FileView.IsDownloading = false;
                    }
                } 
            }
            catch (Exception ex)
            {
                #region Error
                LogEntry l = new LogEntry();
                l.Message = string.Format("{0}", ex.Message);
                l.Title = "FinishWebRequest() Error";
                l.Categories.Add(Category.General);
                l.Priority = Priority.Highest;

                if (ex.InnerException != null) l.ExtendedProperties.Add("InnerException", ex.InnerException.Message);

                CustomLogger.CustomLogger.WriteErrorLog(l);
                #endregion
            }
            finally
            {
                // Close the response and streams objects here to make sure they're closed even if an exception is thrown at some point
                if (response != null) response.Close();
                if (remoteStream != null) remoteStream.Close();
                if (localStream != null) localStream.Close();
            }
        }

2 个答案:

答案 0 :(得分:2)

我不确定它是否适用于所有情况。

但是,当我减少与服务器的并行连接数量以便从3到2下载大文件时,只有没有错误。

(早期我使用了3个并行连接。)

答案 1 :(得分:1)

我遇到了类似的问题,并且能够通过在我的web.config中添加一个行为部分来解决它,它告诉数据合同序列化程序覆盖默认的64kb大小限制。

<behaviors>
  <endpointBehaviors>
    <behavior>
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>

此外,在添加配置后,我开始在客户端收到同样问题的错误,您需要将此配置添加到您的服务和客户端。