locked
Exception: An established connection was aborted by the software in your host machine

    Question

  • I get following exception each time i try communicate:

    System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine

    I have very simple flow:

    1. Send synchronized HTTP request

    2. Call WEB service API in block mode

    3. Send asynchronous HTTP request.

    The third request always fails no matter what i do. All requests are sent to same host though different servlets. Host machine is running Tomcat WEB service within JBoss application server.

    I have .NET 2.0 VS2005 C#. If i run the application with Fiddler working then everything is OK. As stand alone it always fails. Setting KeepAlive property to "false" made no effect.

    If i comment two first calls everything is ticking. If i convert those calls to asynchronous then everything is ticking althoug i get from time to time the same exception. I am tired from this stupid unconditional behavior.

    Please help.

    Monday, August 07, 2006 5:07 PM

Answers

  • Moty is right, in most of the cases this exception indicates something on your machine is blocking your connection. Try running it with firewall/antivirus disabled. This is not permanent, just for testing if this is setup issue or code issue. If it passes without the firewall/antivirus then you have to find a way to allow it through them - add it to the firewall exceptons, etc.

     If this doesn't work the next step is to take a network sniff to see if your request goes out and what's being send on the wire. Post the sniff and/or a code snippet and we will investigate.

    Mariya

    Thursday, August 10, 2006 2:51 PM
    Moderator
  • Eventually everything comes to the fact that the KeepAlive property must be set to False in .NET HTTP communication including WS. .NET does not handle correctly the request for KeepAlive. I stopped using the feature because of the endless synchronization problems. In the case of the synchronous requests the issue can be identified and handled but in the asynchronous requests .NET throws exceptions that have nothing to do with the problem which makes identification and handling procedure impossible.

    So, the answer closing this thread is STOP USING KeepAlive
    Thursday, April 26, 2007 8:30 AM

All replies

  • try to close / disable any antivirus / antispan/ firewall you have.
    Thursday, August 10, 2006 6:40 AM
  • I am working inside the corporate network. The application should run with corporate network environment. What is the reason for me try this? As well i mentioned that the application operates when fiddler (proxy) is activated. I assume the bug is within .NET implementation of the HTTP protocol. My question relates to the patch/fix/workaround of this problem. I see noone from MS guys cannot answer... :(
    Thursday, August 10, 2006 1:48 PM
  • Moty is right, in most of the cases this exception indicates something on your machine is blocking your connection. Try running it with firewall/antivirus disabled. This is not permanent, just for testing if this is setup issue or code issue. If it passes without the firewall/antivirus then you have to find a way to allow it through them - add it to the firewall exceptons, etc.

     If this doesn't work the next step is to take a network sniff to see if your request goes out and what's being send on the wire. Post the sniff and/or a code snippet and we will investigate.

    Mariya

    Thursday, August 10, 2006 2:51 PM
    Moderator
  • Sorry, but neither you nor Moty are right.

    The problem is within asynchronous implementation of the HttpWebRequest class. I reimplemented asynchronous sending by taking HttpWebRequest synchronous version into separate thread and everything works fine now. The problem is clearly inside .NET Framework implementation of the HttpWebRequest. I got an input from the author of the Fiddler sniffer application about problems of the .NET Framework with HTTP/1.1 protocol implementation that relates to continous open socket. I saw that KeepAlive property set to false does not work. Therefore, please, if you can forward the issue to related people it is fine, but do not sell me the stuff about firewall (in the corporate network) or antivirus.

    Sincerely yours, unsatisfied customer.

    P.S. Do not mark a post like yours as an answer.

    Wednesday, August 16, 2006 7:49 AM
  • I also received this error when executing a 2.0 console application.

    I am using system.net.webclient to post a file to secure-HTTP website.

    The code works when debugging, but not when compiled.

    Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.

    Wednesday, August 23, 2006 2:43 PM
  • using (WebClient wc = new WebClient())

    {

    wc.Credentials = credentials;

    wc.Headers.Add("Cookie", "SMCHALLENGE=YES");

    Logger.Log("Web Client URL: " + uri.OriginalString);

    response = System.Text.ASCIIEncoding.ASCII.GetString(wc.UploadFile(uri.OriginalString, objects[0].FilePath));

    if (Environment.UserInteractive)

    {

    for (int HeaderItem = 0; HeaderItem < wc.ResponseHeaders.Count; HeaderItem++)

    {

    Console.WriteLine(wc.ResponseHeaders[HeaderItem].ToString());

    }

    }

    }

    Wednesday, August 23, 2006 2:47 PM
  • Source machine is either XP sp2 or 2000 SP4.

    Target machine is NT4 running ASP.

    Wednesday, August 23, 2006 3:05 PM
  • Folks,
    Sorry for the inconvinience. We can look at this further.
    In order for me to help you I need to things.

    1. A netmon trace [you can download the network monitor from http://www.ethereal.com]
    of the success and failure conditions

    2. A System.Net trace of success and failure conditions. http://blogs.msdn.com/dgorti
    should point you to how to get a trace file. You can send those to me at
    d g o r t i @@@@@@ m i cro so ft ..... com

    and I will take a look at them

     

     

     


    Wednesday, August 23, 2006 4:59 PM
    Moderator
  • No packets are written on failed attempt.

    Since this is port 443 (ssl), the packets are encrypted on successful attempt.

    I'll work on the system.net trace.

    Much Thanks.

    Wednesday, August 23, 2006 6:40 PM
  • Thank you but your suggestion came too late. I moved from using asynchronous methods of the HttpWebRequest i've started using a synchronous version, but in the separate thread. From this moment all my problems were solved. Although i know from using Fiddler and talking to its author that the problem with KeepAlive property still exist in Framework 2.0. The framework identifies droping HTTP request's socket in between connections as an error while it should open a new socket (according to HTTP/1.1 protocol).

    If I will have a time i will try to recover my old code and reproduce the problem. RIght now the only tip i have is to look on asynchronous implementation of the HttpWebRequest. :(

    Thursday, August 24, 2006 9:07 AM
  • Please trust me when I say that we have millions of people who is using async http.
    If stuff is not working I regret it and willing to help. Send the logs and traces as I indicated
    Thursday, August 24, 2006 6:13 PM
    Moderator
  • I lost the "previous" code, but i will try to build a sample and provide you traces. It is important to note that i communicate with JBoss application server on Solaris.
    Tuesday, September 05, 2006 8:00 AM
  • I think I have the same problem.

    I am not using any firewall.

    I am using VS2005 C# with .NET Framework 2.0.50727.

    The server is running on Apache as a cgi.  The service is over SSL and requires basic authentication.

    I have PreAuthenticate = true.  I have a valid certificate and the issuer is trusted.

    When I call using the generated synchronous method, the code works as expected.

    When I call using the generated asynchronous method, the code fails.

    When I call using the generated synchronous method, followed by the asynchronous method, the code works as expected.

    When looking at the traces, in the asynchronous method, after being challanged for Basic authentication, there is an exception.

    System.Net Information: 0 : [0280] Connection#40462388 - Received status line: Version=1.0, StatusCode=401, StatusDescription=Authorization Required.
    System.Net Information: 0 : [0280] Connection#40462388 - Received headers
    {
    Connection: close
    Content-Language: en
    Accept-Ranges: bytes
    Content-Type: text/html; charset=iso-8859-1
    Date: Thu, 07 Sep 2006 03:13:42 GMT
    Server: Apache
    WWW-Authenticate: Basic realm="Test Realm"
    }.
    System.Net Information: 0 : [0280] ConnectStream#5598643::ConnectStream(Buffered -1 bytes.)
    System.Net Information: 0 : [0280] Associating HttpWebRequest#25675301 with ConnectStream#5598643
    System.Net Information: 0 : [0280] Associating HttpWebRequest#25675301 with HttpWebResponse#28367532
    System.Net Information: 0 : [0280] Enumerating security packages:
    System.Net Information: 0 : [0280]     Negotiate
    System.Net Information: 0 : [0280]     Kerberos
    System.Net Information: 0 : [0280]     NTLM
    System.Net Information: 0 : [0280]     Microsoft Unified Security Protocol Provider
    System.Net Information: 0 : [0280]     Schannel
    System.Net Information: 0 : [0280]     WDigest
    System.Net Information: 0 : [0280]     DPA
    System.Net Information: 0 : [0280]     Digest
    System.Net Information: 0 : [0280]     MSN
    System.Net Warning: 0 : [0280] HttpWebRequest#25675301::() - Resubmitting request.
    System.Net Information: 0 : [0280] Associating HttpWebRequest#25675301 with ServicePoint#50130234
    System.Net Information: 0 : [0280] Associating Connection#31950310 with HttpWebRequest#25675301
    System.Net Error: 0 : [0280] Exception in the HttpWebRequest#25675301:: - Unable to connect to the remote server
    System.Net Error: 0 : [0280]    at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
       at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
       at System.Net.Connection.CompleteStartConnection(Boolean async, HttpWebRequest httpWebRequest)
    System.Net Verbose: 0 : [0280] HttpWebRequest#25675301::EndGetResponse()
    System.Net Error: 0 : [0280] Exception in the HttpWebRequest#25675301::EndGetResponse - Unable to connect to the remote server
    System.Net Error: 0 : [0280]    at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
       at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
       at System.Net.Connection.CompleteStartConnection(Boolean async, HttpWebRequest httpWebRequest)

    Working request

    System.Net Information: 0 : [5512] ConnectStream#59332389::ConnectStream(Buffered -1 bytes.)
    System.Net Information: 0 : [5512] Associating HttpWebRequest#523985 with ConnectStream#59332389
    System.Net Information: 0 : [5512] Associating HttpWebRequest#523985 with HttpWebResponse#21605913
    System.Net Information: 0 : [5512] Enumerating security packages:
    System.Net Information: 0 : [5512]     Negotiate
    System.Net Information: 0 : [5512]     Kerberos
    System.Net Information: 0 : [5512]     NTLM
    System.Net Information: 0 : [5512]     Microsoft Unified Security Protocol Provider
    System.Net Information: 0 : [5512]     Schannel
    System.Net Information: 0 : [5512]     WDigest
    System.Net Information: 0 : [5512]     DPA
    System.Net Information: 0 : [5512]     Digest
    System.Net Information: 0 : [5512]     MSN
    System.Net Warning: 0 : [5512] HttpWebRequest#523985::() - Resubmitting request.
    System.Net Information: 0 : [5512] Associating HttpWebRequest#523985 with ServicePoint#25675301
    System.Net Information: 0 : [5512] Associating Connection#52056806 with HttpWebRequest#523985
    System.Net Information: 0 : [5512] TlsStream#646704::.ctor(host=somehost, #certs=0)
    System.Net Information: 0 : [5512] Associating HttpWebRequest#523985 with ConnectStream#31688539
    System.Net Information: 0 : [5512] HttpWebRequest#523985 - Request: POST /some.cgi HTTP/1.1

    System.Net Information: 0 : [5512] SecureChannel#9234571::.ctor(hostname=somehost, #clientCertificates=0)
    System.Net Information: 0 : [5512] SecureChannel#9234571 - Left with 0 client certificates to choose from.
    System.Net Information: 0 : [5512] Using the cached credential handle.

    I hope this enables you to better track down the problem.

     

    I believe this is indeed a problem in the framework.

    Thursday, September 07, 2006 3:59 AM
  • Can you send us the code you are using?
    d g o t i  @@@ m i c r o so ft ......  cc c c c cccc   om
    Thursday, September 07, 2006 7:50 PM
    Moderator
  • /// <summary>
        /// Delegate used as an error event callback.
        /// </summary>
        /// <param name="sender">SendingHttpRequest instance that fired the event</param>
        /// <param name="status">one of <see cref="WebExceptionStatus"/> values</param>
        /// <param name="ex">Instance of <see cref="Exception"/> describing the error.</param>
        public delegate void HttpRequestErrorDelegate(SendHttpRequest sender, WebExceptionStatus status, Exception ex);
        /// <summary>
        /// Delegate used as received data callback.
        /// </summary>
        /// <param name="sender">SendingHttpRequest instance that fired the event</param>
        /// <param name="data">String containing returned data in UTF-8 encoding.</param>
        public delegate void HttpRequestCompleteDelegate(SendHttpRequest sender, string data);

        /// <summary>
        /// Asynchronous sending HTTP request implementation. The class publishes two event handlers: for error handling and
        /// for received data handling. Any error stops request handling and fires the error event. Canceling request
        /// also fires the error event with status WebExceptionStatus.RequestCanceled. This status is also returned when
        /// "unclassifiable error occured". When other than WebException is raised then the WebExceptionStatus.UnknownError
        /// is returned as the status. Although the timeout error is returned with WebExceptionStatus.Timeout the exception
        /// instance is the same as for calling WebRequest.Abort() method.
        /// None of public methods returns immediate results. One must register events' callbacks in order to receive notifications.
        /// </summary>
        public class SendHttpRequest : IDisposable
        {
            private HttpRequestCompleteDelegate callback;
            private Status status = Status.Initiated;
            private ManualResetEvent allDone = new ManualResetEvent(false);

            public static event HttpRequestErrorDelegate OnError;

            /// <summary>
            /// Initiates sending asynchronous HTTP request without data.
            /// </summary>
            /// <param name="uri">Location where to send</param>
            /// <param name="method">Sending method (POST or GET)</param>
            /// <param name="contentType">Registered content type</param>
            /// <param name="timeout">Timeout in seconds to wait before canceling request</param>
            public SendHttpRequest(string uri, string method, string contentType, int timeout, HttpRequestCompleteDelegate callback)
                : this(uri, string.Empty, method, contentType, timeout, callback)
            {
            }

            /// <summary>
            /// Initiates sending asynchronous HTTP request.
            /// </summary>
            /// <param name="uri">Location where to send</param>
            /// <param name="data">String in UTF-8 format containing request's sending data (can be empty)</param>
            /// <param name="method">Sending method (POST or GET)</param>
            /// <param name="contentType">Registered content type</param>
            /// <param name="timeout">Timeout in seconds to wait before canceling request</param>
            public SendHttpRequest(string uri, string data, string method, string contentType, int timeout, HttpRequestCompleteDelegate callback)
            {
                if (timeout < 0)
                    throw new ArgumentOutOfRangeException("timeout", timeout, "Timeout must be positive value"); // ensure that RegisterWaitForSingleObject() does not throw exception
                if (!uri.StartsWith("http"))
                    throw new ArgumentException(uri);
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpRequest.Method = method;
                httpRequest.ContentType = contentType;

                RequestState state = new RequestState();
                state.request = httpRequest;
                state.postData = string.IsNullOrEmpty(data) ? string.Empty : data;

                this.status = Status.Sending;
                this.callback=callback;
                if (state.postData == string.Empty)
                    httpRequest.BeginGetResponse(GetResponseCallback, state);
                else
                    httpRequest.BeginGetRequestStream(GetReadingStreamCallback, state);

                ThreadPool.RegisterWaitForSingleObject(allDone, AllDoneCallback, state, timeout * 1000, true);
            }

            /// <summary>
            /// Cancel request that is in operation.
            /// </summary>
            public void Cancel()
            {
                if (status > Status.Initiated && status < Status.Canceled)
                {
                    status = Status.Canceled;
                    allDone.Set();
                }
            }

            public void Dispose()
            {
                Cancel();
            }

            private void GetReadingStreamCallback(IAsyncResult iar)
            {
                RequestState state = (RequestState)iar.AsyncState;
                try
                {
                    Stream postStream = state.request.EndGetRequestStream(iar);

                    try
                    {
                        byte[] byteArray = Encoding.UTF8.GetBytes(state.postData);
                        postStream.Write(byteArray, 0, byteArray.Length);
                    }
                    finally
                    {
                        postStream.Close();
                    }
                    state.request.BeginGetResponse(GetResponseCallback, state);
                }
                catch (Exception ex)
                {
                    ProcessError(state, ex);
                }
            }

            private void GetResponseCallback(IAsyncResult iar)
            {
                RequestState state = (RequestState)iar.AsyncState;
                try
                {
                    state.response = (HttpWebResponse)state.request.EndGetResponse(iar);
                    state.responseStream = state.response.GetResponseStream();
                    status = Status.Receiving;
                    state.responseStream.BeginRead(state.buffer, 0, state.buffer.Length, ReadCallback, state);
                }
                catch (Exception ex)
                {
                    if (state.response != null)
                        state.response.Close();
                    ProcessError(state, ex);
                }
            }

            private void ReadCallback(IAsyncResult iar)
            {
                RequestState state = (RequestState)iar.AsyncState;

                try
                {
                    int readCount = state.responseStream.EndRead(iar);

                    if (readCount > 0)
                    {
                        state.responseData.Append(Encoding.UTF8.GetString(state.buffer, 0, readCount));
                        state.responseStream.BeginRead(state.buffer, 0, state.buffer.Length, ReadCallback, state);
                    }
                    else
                    {
                        state.responseStream.Close();
                        allDone.Set();
                    }
                }
                catch (Exception ex)
                {
                    state.response.Close();
                    ProcessError(state, ex);
                }
            }

            private void AllDoneCallback(object data, bool timedOut)
            {
                RequestState state = (RequestState)data;

                if (timedOut || this.status == Status.Canceled)
                {
                    if(timedOut)
                        this.status = Status.Timedout;
                    if (state.request != null)
                        state.request.Abort();
                }
                else
                {
                    if (state.error == null)
                    {
                        this.status = Status.Completed;
                        if (this.callback != null)
                        {
                            string response = state.responseData.ToString();

                            if (callback.Target is Control && ((Control)callback.Target).InvokeRequired)
                                ((Control)callback.Target).Invoke(callback, this, response);
                            else
                                callback(this, response);
                        }
                    }
                    else
                    {
                        WebExceptionStatus status = state.error is WebException ? ((WebException)state.error).Status : WebExceptionStatus.UnknownError;
                        NotifyOnError(status, state.error);
                    }
                }
            }

            private void ProcessError(RequestState state, Exception ex)
            {
                if (this.status == Status.Timedout || this.status == Status.Canceled)
                {
                    WebExceptionStatus status = this.status == Status.Timedout ? WebExceptionStatus.Timeout : WebExceptionStatus.RequestCanceled;
                    NotifyOnError(status, ex);
                }
                else
                {
                    state.error = ex; // remember the error and
                    allDone.Set(); // force calling AllDoneCallback()
                }
            }

            private void NotifyOnError(WebExceptionStatus status, Exception ex)
            {
                this.status = Status.Completed;
                if (OnError != null)
                {
                    foreach (HttpRequestErrorDelegate d in OnError.GetInvocationList())
                    {
                        if (d.Target is Control && ((Control)d.Target).InvokeRequired)
                            ((Control)d.Target).Invoke(d, this, status, ex);
                        else
                            d(this, status, ex);
                    }
                }
            }

            /// <summary>
            /// Status enumerator defines instance status. For internal use only
            /// </summary>
            private enum Status
            {
                Initiated,
                Sending,
                Receiving,
                Canceled,
                Timedout,
                Completed
            }

            /// <summary>
            /// All necessary info for asynchronous handling of the HTTP request
            /// </summary>
            class RequestState
            {
                private const int BUFFER_SIZE = 1024;
                public HttpWebRequest request;
                public HttpWebResponse response;
                public byte[] buffer; // buffer to read response stream
                public string postData; // sending data
                public StringBuilder responseData; // receiving data
                public Stream responseStream;
                public Exception error;

                public RequestState()
                {
                    buffer = new byte[BUFFER_SIZE];
                    responseData = new StringBuilder();
                }
            }
        }

    Sunday, September 10, 2006 10:34 AM
  • I hope it is clear enough. The class sends asynchronous request from constructor and calls a delegate once the sending is over. It has error handling event that is common for all users of the class. I know that is is not the best design possible.... :-/

    Sunday, September 10, 2006 10:36 AM
  • I'm having the same problem.  I'm making asynchronous calls to a web-service which is hosted in Apache.  My environment is Visual Studio 2005, and I'm currently running everything through the ASP.NET Development Server.  It only happens every once in a while.  I thought maybe it had something to do with garbage collection (similar to making an asynchronous call on a socket, passing the socket as that call's state, and not keeping a reference to the socket anywhere else in the code)  but that doesn't seem to be the case.

    Here's some sample code:

    <WebMethod()> Public Function BeginCSAIn(ByVal VisitID As Long, ByVal RFID As String, ByVal LaneID As String, ByVal Callback As AsyncCallback, ByVal State As Object) As IAsyncResult

      Dim Method As New Navis.BizMethod("SUBMIT_TRUCK_AT_CHS_YARD_IN")

      Method.Params.Add("tvGkey", VisitID)

      Method.Params.Add("cheAeiTagId", RFID)

      Method.Params.Add("hwLaneId", LaneID)

      Return Method.Execute(Callback, State)

    End Function

    <WebMethod()> Public Sub EndCSAIn(ByVal Result As IAsyncResult)

       Navis.BizMethod.GetResponse(Result)

    End Sub

    Here's an example of the exception I get:

    System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
       at System.Net.Sockets.Socket.MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags)
       at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)
       --- End of inner exception stack trace ---
       at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)
       at System.Net.PooledStream.MultipleWrite(BufferOffsetSize[] buffers)
       at System.Net.Connection.Write(ScatterGatherBuffers writeBuffer)
       at System.Net.ConnectStream.ResubmitWrite(ConnectStream oldStream, Boolean suppressWrite)
       --- End of inner exception stack trace ---
       at System.Web.Services.Protocols.WebClientAsyncResult.WaitForResponse()
       at System.Web.Services.Protocols.WebClientProtocol.EndSend(IAsyncResult asyncResult, Object& internalAsyncState, Stream& responseStream)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.EndInvoke(IAsyncResult asyncResult)
       at BizPortal.BizPortalClientService.EndprocessSoapRequest(IAsyncResult asyncResult) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\navisproxy\aecb88fa\1bcd3ce5\App_WebReferences.zqjuulsg.0.cs:line 67
       at Navis.BizMethod.GetResponse(IAsyncResult Result, Boolean AutoException) in C:\Development\SDR\NAVIS\NavisProxy\App_Code\BizMethod.vb:line 194
       at Proxy.EndCSAIn(IAsyncResult Result) in C:\Development\SDR\NAVIS\NavisProxy\App_Code\Proxy.vb:line 254

     

    Thursday, October 05, 2006 4:11 PM

  • I have seen the same thing - always seems to be in conjunction with async web requests or an async SOAP request.  It isn't guaranteed to be repeatable, but it does go away if I change the async request to a synchronous one.  I tried to generate a little test program to reproduce it, but haven't had any luck.

    I also noticed another errors that I believe are manifestations of the same problem - we are using the TraceExtension found on MSDN for our SOAP client, and occassionally it will throw an exception that the socket has already been disposed.

    We are using Apache on the server side, and we are not using SSL when this occurs.

    Friday, October 27, 2006 8:45 PM
  • I have a similar problem, but I am not using asynchronous web requests or web services.  Take a look at the following code:  Submit.aspx is just the default aspx page that is created in VSWD 2005.  In the following example, the first call to ws.Write succeeds.  The next call fails with the "underlying connection closed" error.  I am downloading ethereal to see if I can figure out more; unless one of you guys already sees the problem.

    Dim req As HttpWebRequest = HttpWebRequest.Create("http://localhost:3494/upload/submit.aspx")

    req.AllowWriteStreamBuffering = False

    req.Method = "POST"

    Dim fs As New FileStream("c:\file.txt", FileMode.Open, FileAccess.Read)

    fs.Seek(0, SeekOrigin.Begin)

    req.ContentLength = fs.Length

    Dim fdata(1028) As Byte

    Dim ws As Stream = req.GetRequestStream()

    Dim bytesRead As Integer = 0

    Do

       bytesRead = fs.Read(fdata, 0, 1028)

       If bytesRead > 0 Then

          ws.Write(fdata, 0, bytesRead)

          Array.Clear(fdata, 0, 1028)

       Else

          Exit Do

       End If

    Loop

    Dim resp As HttpWebResponse = req.GetResponse()

    fs.Close()

    ws.Close()

    resp.Close()

    Sunday, December 10, 2006 7:32 PM
  • i turned on System.Net tracing and here are the important parts:

     

    System.Net Information: 0 : [7024] ConnectStream#35567111 - Sending headers
    {
    Host: localhost:3494
    Content-Length: 3570019
    Expect: 100-continue
    Connection: Keep-Alive
    }.
    System.Net Information: 0 : [7024] Connection#14421545 - Received status line: Version=1.1, StatusCode=100, StatusDescription=Continue.
    System.Net Information: 0 : [7024] Connection#14421545 - Received headers
    {
    Content-Length: 0
    Date: Sun, 10 Dec 2006 20:17:16 GMT
    Server: ASP.NET Development Server/8.0.0.0
    }.
    System.Net Information: 0 : [7024] Connection#14421545 - Received status line: Version=1.1, StatusCode=200, StatusDescription=OK.
    System.Net Information: 0 : [7024] Connection#14421545 - Received headers
    {
    Connection: Close
    Content-Length: 486
    Cache-Control: private
    Content-Type: text/html; charset=utf-8
    Date: Sun, 10 Dec 2006 20:17:16 GMT
    Server: ASP.NET Development Server/8.0.0.0
    X-AspNet-Version: 2.0.50727
    }.

    Look at the headers that were received in red.  Why is the Connection: Close portion of the header there?  Again, I am using the code posted in my last thread.  I do not understand where the close header is coming from.  Any help would be great.

     

    Sunday, December 10, 2006 8:33 PM
  • Ok ... I managed to get it to work.  I decided to setup an ASP.NET IHttpHandler and return a StatusCode=100 ... this will return the continue response that the client is looking for.  Now my question is this:  In the ProcessRequest method, I am trying to read the data from the context.Request.InputStream property.  This stream's length is > 0 only after all data is sent from the client.  So if the loop in my code Writes 1000 times.  The InputStream will remain empty until the loop completes and the request stream is closed (on the client).  Is there any way to have the request stream force to transfer to the server (cause InputStream to have data)?
    Monday, December 11, 2006 5:36 AM
  • Hi,

    Even i am facing same kinda problem. can anyone help out with a code snippet??

    I am trying to upload a tif image filr from my appln to a remote server..

    Please help me out.

     

    Tuesday, January 02, 2007 10:59 AM
  • Hey Hi,       Did u get a solution for ur problem???if yes, can u send me the code for the same as i have a similar situation down here!thnx in advance!!!Dinesh
    Monday, April 16, 2007 7:16 AM
  • Hello,

    I had the following problem: a ASP.NET 2 WebService on a W2K server on the internet, and a WinForms client consuming the service.
    The first call I made was an async call, and I always got a "The underlying connection was closed: An unexpected error occurred on a send" with in the detail "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine".

    I solved it by:
    a) creating an inherited class from my webservice proxy, and in that class setting the KeepAlive to False (there are quite a lot of articles on the Net describing this, although the all refer to .NET 1.1).
    b) creating a dummy webmethod GetVersion that returns a string (it really doesn't matter how it's called or what it returns) and calling that method first synchronously.

    The combination of these both elements solved it for me. Only a) without b) or b) without a) didn't do it.

    Just wanted to share this bit of information, in case someone else encounters the same problem.

    X.

    Thursday, April 19, 2007 12:20 PM

  • I think I found the cause of the problem in our app - we were setting KeepAlive to false, and it was working fine.  But in the client, we had a default value for the MaxServicePointIdleTime (which I think ends up being 100 seconds), and our Apache web server was configured to close the connection after 15 seconds.  So in the right circumstances, if we sent a SOAP request to the server and then sent another SOAP request or an HTTP request, it could reuse the connection.  If this happened after 15 but before 100 seconds, the web server responded with a connection closed error.  Setting

        System.Net.ServicePointManager.MaxServicePointIdleTime = 10000;

    (it's in milliseconds) in the application domains that were generating SOAP and HTTP requests fixed the problem.

    • Proposed as answer by Mihaila Tuesday, January 17, 2012 1:40 PM
    Thursday, April 19, 2007 4:16 PM
  • Eventually everything comes to the fact that the KeepAlive property must be set to False in .NET HTTP communication including WS. .NET does not handle correctly the request for KeepAlive. I stopped using the feature because of the endless synchronization problems. In the case of the synchronous requests the issue can be identified and handled but in the asynchronous requests .NET throws exceptions that have nothing to do with the problem which makes identification and handling procedure impossible.

    So, the answer closing this thread is STOP USING KeepAlive
    Thursday, April 26, 2007 8:30 AM
  • That isn't the only answer.  I had KeepAlive turned off for months, and we were still having the problem.  Even with KeepAlive off, if you don't adjust the MaxServicePointIdleTime, you can still get "remote server has closed connection" errors.
    Thursday, April 26, 2007 9:19 PM
  • It may happened only because in the implementation M$ may not close the connection. However, if we believe to MSDN documentation then it makes no sense because that property is not connected to keeping connection mechanism. :-)
    Anyway, thank you for your info. I will follow up the situation and try to use that in the case of the "remote host has closed connection" error.

    Sunday, April 29, 2007 7:52 AM
  • After nearly two days of beating my head against this wall, I stumbled on this post.  What a life saver!  Works like a charm, thanks much bithead_bob!
    Friday, July 20, 2007 6:28 AM
  • Note:

     

    Microsoft now has a hotfix for this problem with Win 2003 and XP:

     

    Win2003:http://support.microsoft.com/kb/931319/

     

    WinXP:http://support.microsoft.com/kb/938566/en-us

     

    Wednesday, August 08, 2007 9:30 AM
  • Hi ,

    I am getting the same error but my code is in VB.net,I am creating application server. I am pasting my code, I am not able to get the reason of the error , Pleasae help me to find the error.

    Error i ma getting is

    "Exception Type        : System.Net.Sockets.SocketException
    Exception Information : Message Parser - Error in parsing.
    Exception Description : An established connection was aborted by the software in your host machine "

     

     

    Tuesday, August 21, 2007 12:31 PM
  •  

    Even after applying this hotfix we are facing the same problem.
    Tuesday, August 21, 2007 9:06 PM
  • Hi , I am also getting the same exception inmy code which is a console based application. if I do netstat then I found that port some of teh port are in CLOSE_WAIT state. My Exception detail is

     

    Exception Type        : System.Net.Sockets.SocketException
    Exception Information : Message Parser - Error in parsing.
    Exception Description : An established connection was aborted by the software in your host machine

    Stack Trace           :    at System.Net.Sockets.Socket.Send (Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

      at System.Net.Sockets.Socket.Send(Byte[] buffer)

      at MessageParser.WU.Parser.SendToClient (Boolean pCommitFlag)

      at MessageParser.WU.Parser.StartProcessing()


    Can any one help me . Please reply sonn

    Thanks in advance

    Wednesday, August 22, 2007 2:22 PM
  • Hi , I am also getting the same exception inmy code which is a console based application. if I do netstat then I found that port some of teh port are in CLOSE_WAIT state. My Exception detail is

     

    Exception Type        : System.Net.Sockets.SocketException
    Exception Information : Message Parser - Error in parsing.
    Exception Description : An established connection was aborted by the software in your host machine

    Stack Trace           :    at System.Net.Sockets.Socket.Send (Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

      at System.Net.Sockets.Socket.Send(Byte[] buffer)

      at MessageParser.WU.Parser.SendToClient (Boolean pCommitFlag)

      at MessageParser.WU.Parser.StartProcessing()


    Can any one help me . Please reply sonn

    Thanks in advance

    divya
    Wednesday, August 22, 2007 2:22 PM
  • Hi , I am also getting the same exception inmy code which is a console based application. if I do netstat then I found that port some of teh port are in CLOSE_WAIT state. My Exception detail is

     

    Exception Type        : System.Net.Sockets.SocketException
    Exception Information : Message Parser - Error in parsing.
    Exception Description : An established connection was aborted by the software in your host machine

    Stack Trace           :    at System.Net.Sockets.Socket.Send (Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)

      at System.Net.Sockets.Socket.Send(Byte[] buffer)

      at MessageParser.WU.Parser.SendToClient (Boolean pCommitFlag)

      at MessageParser.WU.Parser.StartProcessing()


    Can any one help me . Please reply sonn

    Thanks in advance

    divya
    Wednesday, August 22, 2007 2:22 PM
  • i am trying to use Heroku for facebook apps and get the same problem when try to login !
    Egyptian discussion forums for news, media, sports, movies and more ....
    Wednesday, December 14, 2011 6:37 PM
  • problem solved when disabled the antivirus :)
    Egyptian discussion forums for news, media, sports, movies and more ....
    • Proposed as answer by tito5300 Monday, January 09, 2012 9:57 PM
    • Unproposed as answer by tito5300 Monday, January 09, 2012 9:57 PM
    Wednesday, December 14, 2011 6:55 PM
  • Egyptian discussion forums for news, media, sports, movies and more ....
    • Edited by tito5300 Monday, January 09, 2012 9:59 PM
    Monday, January 09, 2012 9:59 PM
  • God bless you.

    I was frustrated looking how the code was laughing on me, because 2 times it was working ok and the third it was replying error ...

    So your setting works just fine for me .

    Thanks!

     

    P.S. and it is one of the few times when MSDN really helped me. and it wasn't even MS and his big army of developers, it was one lonely soldier of code .

     

    • Edited by Mihaila Tuesday, January 17, 2012 1:44 PM
    Tuesday, January 17, 2012 1:42 PM