locked
Exception: "The underlying connection was closed: The connection was closed unexpectedly." (sometimes)

    Question

  • I have a windows app connecting to a webservice.  In some situation(s) (haven't narrowed it down enough), I get the following exception:

    The underlying connection was closed: The connection was closed unexpectedly.

    When this exception is thrown, it is calling a method of a web reference.

    Now the situation that we experience this is on a laptop in the field that is using a WWAN connection in at least one location.  It works fine in the lab at the office.  Anyone have any ideas what could be causing this?

    Wednesday, January 18, 2006 9:58 PM

Answers

  • The analysis above is pretty much right.  The .NET HTTP implementation tries to keep the connection alive as long as possible in order to avoid the overhead of creating a new conneciton.  If the server decides to close the connection without notifying the client you may see this error.  In general, you need to catch these exceptions in your application and create a new connections as necessary.  The client proxy code is not really related other than by the fact that it uses the .NET HTTP implementation.

    There is a server side connection timeout in ASP.NET that you can configure, and it may be causing this problem.  See:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfhttpruntimesection.asp

    Daniel Roth

    Thursday, January 19, 2006 3:51 PM
    Moderator
  • Dear Jörg Jooss And All

    You are perfectly right with your statements. The server never disconnectes on its own without sending the Connection :close.

    Even I am trying to say the same thing only I feel I am not able to convey the message in proper way. So I have logged the data that I am talking about and I will explain you with its context.

    First some basics.

    According to the urs provided in previous post of HTTP continue 100 the beheviour of the client server has to be as follows.


    Client Sends :
        Expect: 100-continue  (Ask server are you ready to process my information)

    Server sends :
        HTTP/1.0 100 Continue (server says yes I am readey)
        and if it has already received the further message it processes it
        and gives the expected response
        and then
        Connection: close
        and get disconnected
    Client send :
        Sends the request
    Server Sends
        Response.

     In ideal conditions i.e. at a proper speed server gets the expected continue and the request at the same time from .Net and send back the response to the client. That why in the begening of the thread it is said that it works fine in the office internet connection but dont work on laptop.

    OK Until now everything is fine.

    No as expected above Client sends expect:100 server send Continue Client sends request. server sends response
    You all will agree with me for above statement.

    NOW LEST SEE WHAT DOT.NET DOES WITH THE ABOVE SCENARIO


    The following statements are captured by me by creating a net sniffer in VB6




    12:03:25 PM:wskLocal Connected

    12:03:25 PM:wskRemote Connected

    12:03:25 PM:wskLocal Data arrived:
    POST http://www.webservicex.net/whois.asmx HTTP/1.1
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.42)
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://www.WebserviceX.NET/GetWhoIS"
    Host: www.webservicex.net
    Content-Length: 332
    Expect: 100-continue
    Proxy-Connection: Keep-Alive

    12:03:25 PM:wskLocal Data arrived:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetWhoIS xmlns="http://www.WebserviceX.NET"><HostName>yahoo.com</HostName></GetWhoIS></soap:Body></soap:Envelope>

    12:03:26 PM:wskRemote Data arrived:
    HTTP/1.0 100 Continue
    Connection: close
    Via: 1.1 Fivenetwork (NetCache NetApp/5.5R5), 1.1 Webcat (tinyproxy/1.7.5)
    Date: Wed, 22 Feb 2006 06:51:09 GMT
    12:03:26 PM:wskRemote Closed



    As you can see above .Net is sending first Expect 100 in one senddata of socket then send the actual request


    So the Server Responds back with Continue 100. And exactly here .Net is showing message "Underlying connection was close. Connection was closed unexpectedly"
    .Net is under impression that it has anyway already sent the data but server sent Connection : Close so it shows error without resending the request.

    For same request above I tried several times and I use to get a proper response from the server few times.


    So the solution for the above that worked for me was

        System.Net.ServicePointManager.Expect100Continue = False

    So .Net is not asking for expect continue hence server is waiting to receive the complete data and is responding back with the response.


    Please let me know if above information finds ok for you all. If any modification or clarification required please feel free to bother me.
    Saturday, February 25, 2006 3:54 AM

All replies

  • If you are transfering large messages or the operation on the service side is taking very long you may enter into a timeout situation that you can change in ASP.NET configuration.

    Please describe the frameowrk that you are using: SoapToolkit, WSE, ASMX?

    Hope this helps,

    Diego Gonzalez, [C#, MVP]

    Lagash Systems SA

    Thursday, January 19, 2006 12:35 AM
    Moderator
  • Webservice is ASMX in .NET 2.0.  Originally .NET 1.1 with same problem.  Client app is .NET 2.0.  Both written in C#.

    The timeout on the client app should be the default 100,000ms.  Is there also a timeout setting on the webservice side?  Note that the exception is thrown within a second of invoking the web method.

    Thursday, January 19, 2006 3:48 AM
  • IMHO this is the most common error and the one I have not seen any clear info on how to stop it.

    *I THINK*  based on my reading that it has some what to do with http 1.1 and keep-alives.  it may also have to do with the client proxy code generated by the "add web ref" in Visual studio. 

    *I THINK*  that what happens is that the .net client app thinks a connection is open and tries to use it and gets a connection closed error. I think we might want some logic that catches that and tries to create a new connection and if that new connection works go on and just use it.  if it fails then do a Throw .....

    but this is just my best guesses based on what I have seen so far.

    now if we could get someone from Microsoft who knows what the logic is for the whole round-trip they might be able to give more insight on this.

    Thursday, January 19, 2006 3:10 PM
  • The analysis above is pretty much right.  The .NET HTTP implementation tries to keep the connection alive as long as possible in order to avoid the overhead of creating a new conneciton.  If the server decides to close the connection without notifying the client you may see this error.  In general, you need to catch these exceptions in your application and create a new connections as necessary.  The client proxy code is not really related other than by the fact that it uses the .NET HTTP implementation.

    There is a server side connection timeout in ASP.NET that you can configure, and it may be causing this problem.  See:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfhttpruntimesection.asp

    Daniel Roth

    Thursday, January 19, 2006 3:51 PM
    Moderator
  • How do you manually force the web reference to create a new connection?

    What is the default HTTP ExecutionTimeout?  (ExecutionTimeout is the one I should be concerned with, right?  Not sure what App domain is.)

    Thursday, January 19, 2006 5:04 PM
  •  Daniel Roth wrote:

    The analysis above is pretty much right.  The .NET HTTP implementation tries to keep the connection alive as long as possible in order to avoid the overhead of creating a new conneciton.  If the server decides to close the connection without notifying the client you may see this error.  In general, you need to catch these exceptions in your application and create a new connections as necessary.  The client proxy code is not really related other than by the fact that it uses the .NET HTTP implementation.

    There is a server side connection timeout in ASP.NET that you can configure, and it may be causing this problem.  See:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfhttpruntimesection.asp

    Daniel Roth

    I have been thinking that with the "General Case" of wanting to try and create a new connection on failure that there should be a generalized way to write that code one time and make adding that to the calls to the web service as simple and painless as possible.

    I wonder if other folks are out there writing this code and we are all "re-inventing the wheel" right now.

    I have not spent much time hacking the code that calls the web service.....

    it would be usefull to have some example of how to tell the local proxy that makes the calls to use/create/generate a connection.

     

    like can we make a call:

    WSproxy.ReConnect();

    do we need to create a http/webrequest objects and somehow plug them into the proxy??

    how does the first call start a connection?

    how does the proxy class "track" it's state (Connected, not connected)

     

    Thursday, January 19, 2006 7:05 PM
  •  Daniel Roth wrote:

    The analysis above is pretty much right.  The .NET HTTP implementation tries to keep the connection alive as long as possible in order to avoid the overhead of creating a new conneciton.  If the server decides to close the connection without notifying the client you may see this error.  In general, you need to catch these exceptions in your application and create a new connections as necessary.  The client proxy code is not really related other than by the fact that it uses the .NET HTTP implementation.

    There is a server side connection timeout in ASP.NET that you can configure, and it may be causing this problem.  See:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfhttpruntimesection.asp

    Daniel Roth

     

    a follow on question:

     

    when is the first connection created?

    is it when the first service call is made?

    or is it when the client proxy class is created with wsfoo = new wsfoo() ?

    right now I have some code that I am re-working and was thinking:

    perhaps in place of creating a global level object on start up perhaps I should be doing that later and new /  dispose the object locally ??

    that would cause my app to create a new object just before it goes to call the method so the connection and timeout would start then and be less prone to reaching a timeout.... ( I hope)

    also I am still looking for what code to use to make a new connection??

    looks like I have to cast the local client proxy down to a lower level web request class and then do a webconnection create thing ??

    as far as I have seen the top level class built by add-web-ref does not expose properties like:

    bool IsConnected ?

    or methods like:

    Service.Connect( URL );

    or .Open()  .Close() like on a file or stream ??

     

    Friday, January 20, 2006 3:41 PM
  • I think I figured out what the problem is, but I haven't found a good solution for it.

    In my code:

    webservice.MyWS ws1 = new webservice.MyWS();
    try
    {
         ws1.Get();
    }
    catch(Exception ex)
    {
         System.Diagnostics.Debug.Writeline(ex.Message);
    }

     

    It seems that an exception is thrown when the web service isn't ready.  So by retrying the webmethod, it eventually works.

    webservice.MyWS ws1 = new webservice.MyWS();
    int i = 0;
    Retry:
    try
    {
         ws1.Get();
    }
    catch(Exception ex)

         System.Diagnostics.Debug.Writeline(ex.Message);
         if (i < 3)
         {
              i++;
              goto Retry;
         }
    }

    Is there a way to check to see whether the webservice is ready?  And or wait for it to initialize?

    Tuesday, January 24, 2006 11:40 PM
  •  .NET Developer wrote:

    I think I figured out what the problem is, but I haven't found a good solution for it.

    In my code:

    webservice.MyWS ws1 = new webservice.MyWS();
    try
    {
         ws1.Get();
    }
    catch(Exception ex)
    {
         System.Diagnostics.Debug.Writeline(ex.Message);
    }

     

    It seems that an exception is thrown when the web service isn't ready.  So by retrying the webmethod, it eventually works.

    webservice.MyWS ws1 = new webservice.MyWS();
    int i = 0;
    Retry:
    try
    {
         ws1.Get();
    }
    catch(Exception ex)

         System.Diagnostics.Debug.Writeline(ex.Message);
         if (i < 3)
         {
              i++;
              goto Retry;
         }
    }

    Is there a way to check to see whether the webservice is ready?  And or wait for it to initialize?

     

    just one thing:  goto??

    I'd do a while loop like this:

    TryCount =0;
    Ready=False;

    While ( ! Ready && TryCount < 5){

    bool flag=false;
      try {

    ws.get()

      }
      catch{
           flag=true;

      }

    TryCount++;

    if (flag){

    //  stuff here

    }
    else{

    Ready=True;

    }
    }

    if ( !Ready && TryCount>4){
    //  throw something
    }

     

    a bit more logic there but I think that gives a clear flow of

    "If at first you don't sucseed Try Try Again"

    and a final  Throw for total failure cases.

    Wednesday, January 25, 2006 5:13 PM
  • This is the right idea.  To recover from loss of the connection you need to catch the exception and retry the request as appropriate for your application.  The original request may have partially complete so it really is up to your application to decide if retrying the request is appropriate.

    I don't have a well crafted example for how you should write the code to retry the request.  I'm going to move this thread to the networking web forum where they might be able to supply this code.

    I agree that it might be an interesting feature to be able to turn on automatically retrying the request if you know that it will always be safe to do so for your application.

    Thanks.

     Daniel Roth

    Sunday, January 29, 2006 7:18 AM
    Moderator
  • Daniel, can you post a link to the thread here?
    Friday, February 10, 2006 9:27 PM
  • Well I found the problem (not solution yet)


    The above problem is because of  following

    While sending soap request to server .Net is sending following through TCPIP socket first

    POST http://Someserver.com/Somefile.asmx HTTP/1.1
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.42)
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://nettime.centralservers6.com/cs/NetTimeServices/Punch"
    Host: nettime.centralservers6.com
    Content-Length: 922
    Expect: 100-continue
    Proxy-Connection: Keep-Alive



    Then sends the actual Soap xml after a fraction of delay.

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
    <SomeXML/>
    </soap:Body>
    </soap:Envelope>

    As you can notice in above it is sending Expect 100:Continues to the server so server send  back the continue 100 and closes the connection socket (This is default beheviour of any web server check : Html 10 Status Code Definitions )

    As server closes the connection .Net displays The connection was closed unexpectedly. But according to the design of server its expected for server to send continue and close the connection once it received "Expect 100:continue"

    So i feel this is a bug.

    For above I had developed a Net Sniffer in VB.6.0 and made the .Net proxy to connect to my NetSniffer and my netsniffer was connected to internet. By this way I was able to know what headers it was sending to the webserver


    Following link might take you further to the solution.
    http://support.microsoft.com/default.aspx?scid=kb;en-us;327885
    Thursday, February 23, 2006 4:38 AM
  • The server isn't supposed to close the connection by design. No HTTP status code has any implications for connection management. This is actually a completely separate topic. 100 means:

    The client SHOULD continue with its request. This interim response is used to inform the client that the initial part of the request has been received and has not yet been rejected by the server. The client SHOULD continue by sending the remainder of the request or, if the request has already been completed, ignore this response. The server MUST send a final response after the request has been completed. See section 8.2.3 for detailed discussion of the use and handling of this status code.

    You can disable Expectations by setting System.Net.ServicePontManager.Expect100Continue to false.

    Thursday, February 23, 2006 9:32 AM
  • Dear Joss

    First the good news. That the problem stated in thread is solved.

    As I mentioned earlier that  "Server Disconnects" i still stand with my word. What i mean to say i that the server disconnects the Port on which it was connected to client.
     And this is rather the architecture of any WEB server.

    1. Connect 2. Get Request 3. Send response 4. Close


    If you click for any request to web browser every request is considered diffrently.


    Thanks and regards
    Sachin Chavan.


    Thursday, February 23, 2006 12:31 PM
  • In HTTP 1.1, TCP connections are persistent by default. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1 for details.

    But that's only the spec -- if you see that your server disconnects and doesn't send Connection: close with the response, it is a problem, no doubt about it.

    Thursday, February 23, 2006 1:29 PM
  • I am glad that your problem is solved.  Could you please post what you did to solve it so that others can learn from your experience.

    Now, in version 1.0 of the HTTP RFC, the connection was closed after each request by many server implementations.  In HTTP 1.1, this is not the case.  The connection is kept alive unless either the client or server sends the "Connection: Close" header.  See http://www.ietf.org/rfc/rfc2616.txt?number=2616 section 14.10 for more details.  It specifically states:

    HTTP/1.1 applications that do not support persistent connections MUST include the "close" connection option in every message.

     

    Friday, February 24, 2006 5:35 PM
    Moderator
  • Dear Jörg Jooss And All

    You are perfectly right with your statements. The server never disconnectes on its own without sending the Connection :close.

    Even I am trying to say the same thing only I feel I am not able to convey the message in proper way. So I have logged the data that I am talking about and I will explain you with its context.

    First some basics.

    According to the urs provided in previous post of HTTP continue 100 the beheviour of the client server has to be as follows.


    Client Sends :
        Expect: 100-continue  (Ask server are you ready to process my information)

    Server sends :
        HTTP/1.0 100 Continue (server says yes I am readey)
        and if it has already received the further message it processes it
        and gives the expected response
        and then
        Connection: close
        and get disconnected
    Client send :
        Sends the request
    Server Sends
        Response.

     In ideal conditions i.e. at a proper speed server gets the expected continue and the request at the same time from .Net and send back the response to the client. That why in the begening of the thread it is said that it works fine in the office internet connection but dont work on laptop.

    OK Until now everything is fine.

    No as expected above Client sends expect:100 server send Continue Client sends request. server sends response
    You all will agree with me for above statement.

    NOW LEST SEE WHAT DOT.NET DOES WITH THE ABOVE SCENARIO


    The following statements are captured by me by creating a net sniffer in VB6




    12:03:25 PM:wskLocal Connected

    12:03:25 PM:wskRemote Connected

    12:03:25 PM:wskLocal Data arrived:
    POST http://www.webservicex.net/whois.asmx HTTP/1.1
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.42)
    Content-Type: text/xml; charset=utf-8
    SOAPAction: "http://www.WebserviceX.NET/GetWhoIS"
    Host: www.webservicex.net
    Content-Length: 332
    Expect: 100-continue
    Proxy-Connection: Keep-Alive

    12:03:25 PM:wskLocal Data arrived:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetWhoIS xmlns="http://www.WebserviceX.NET"><HostName>yahoo.com</HostName></GetWhoIS></soap:Body></soap:Envelope>

    12:03:26 PM:wskRemote Data arrived:
    HTTP/1.0 100 Continue
    Connection: close
    Via: 1.1 Fivenetwork (NetCache NetApp/5.5R5), 1.1 Webcat (tinyproxy/1.7.5)
    Date: Wed, 22 Feb 2006 06:51:09 GMT
    12:03:26 PM:wskRemote Closed



    As you can see above .Net is sending first Expect 100 in one senddata of socket then send the actual request


    So the Server Responds back with Continue 100. And exactly here .Net is showing message "Underlying connection was close. Connection was closed unexpectedly"
    .Net is under impression that it has anyway already sent the data but server sent Connection : Close so it shows error without resending the request.

    For same request above I tried several times and I use to get a proper response from the server few times.


    So the solution for the above that worked for me was

        System.Net.ServicePointManager.Expect100Continue = False

    So .Net is not asking for expect continue hence server is waiting to receive the complete data and is responding back with the response.


    Please let me know if above information finds ok for you all. If any modification or clarification required please feel free to bother me.
    Saturday, February 25, 2006 3:54 AM
  • i have the same exact problem,, i tried something else.. totally different and it worked so far.. check my post:

    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=269078&SiteID=1

     

    Saturday, February 25, 2006 9:11 PM
  • SachinChavan.in,

    >Server sends :
    >    HTTP/1.0 100 Continue (server says yes I am readey)
    >    and if it has already received the further message it processes it
    >    and gives the expected response
    >    and then
    >    Connection: close
    >    and get disconnected

    First of all, expectations are a HTTP 1.1 feature, thus the origin server must reply with HTTP/1.1 100 Continue.

    Secondly, closing the connection at this point is not required in HTTP 1.1, although it may happen—say, if persistent connections are disabled altogether, the number of file descriptors reserved for persistent connections are currently exhausted, or the response doesn't contain a Content-Length header or isn't chunked.

    Which brings us to your HTTP capture:

    >HTTP/1.0 100 Continue
    >Connection: close
    >Via: 1.1 Fivenetwork (NetCache NetApp/5.5R5), 1.1 Webcat (tinyproxy/1.7.5)
    >Date: Wed, 22 Feb 2006 06:51:09 GMT
    >12:03:26 PM:wskRemote Closed

    What we have here is most likely a HTTP 1.0 interoperability issue with tinyproxy. If you're interested in all the details, see chapter 4 of this book. It takes (p)ages to explain…

    If you're able to bypass that proxy, try again with expectations enabled. 

     

    Sunday, February 26, 2006 10:41 AM
  • Dear Joss,

    Have you tested to connct to your webservice locally , on your computer?

    Is your problem due to micro cuts of your connection, in such a case, you'd better contact your ISP?

    I think, in such a case that you'd better:
    - set an error catching when you set a dialog when your webservice.
    - set a buffer of information in your web service that you wipe when the whole information is get and treated.
    - set a "session memory" (with a timeout) in your web service as to reconnect with the same session Id.
    - if the connection is interrupted set an error catching to reset connection (with the same session Id) and then to send more of your request when it's cutting off

    Regards

    Tukkkko
    Architect
    ALTI
    Sunday, February 26, 2006 10:02 PM
  • hi..............please help me , i got this problem ...so long....i can't  solve it...

    i also got this problem to connecto to service written by MAINFRAME'S SYSTEM..

    sometime it's successful, but sometime it will fail....

    can you give me some sugguestion to my code?? 

    thank you...

    ps: i use custom defined library (function) written by .net , to call the mainframe's system, and my code as following :

    public string callService(string postData){

                System.Net.ServicePointManager.Expect100Continue = false;

                HttpWebRequest httpReq = null;
                HttpWebResponse httpResp = null;
                System.Uri httpURL = new Uri(url);
                httpReq = (HttpWebRequest)WebRequest.Create(httpURL);

    httpReq .ProtocolVersion=HttpVersion.Version10;   // reference from http://geekswithblogs.net/denis/archive/2005/08/16/50365.aspx
                httpReq.Timeout = 1000000;
                httpReq.ReadWriteTimeout = 1000000;
                    httpReq.Method = "POST";
                    httpReq.KeepAlive = false;  // reference from other website

                    httpReq.ContentType = "application/x-www-form-urlencoded";
                    StreamWriter StreamWriter1 = new StreamWriter(httpReq.GetRequestStream(), System.Text.Encoding.GetEncoding("Big5"));
                    StreamWriter1.Write(postData);
                    StreamWriter1.Close();
                httpResp = (HttpWebResponse)httpReq.GetResponse();
                Stream respStream = httpResp.GetResponseStream();
                StreamReader reader = new StreamReader(respStream, System.Text.Encoding.Default);
                string result = reader.ReadToEnd();
                httpResp.Close();
                httpReq.Abort();
                httpReq = null;
                httpResp = null;
                return result;

    }

     

    Tuesday, January 02, 2007 4:39 AM
  • Please don't hijack an old thread—create a new one.

    First of all, what is the exact error?

    Some questions/comments regarding in your code:

    • Why the call to HttpWebRequest.Abort()?
    • Note that it's sufficient to set ServicePointManager.Expect100Continue once in your application (e.g. on startup).
    • Why do you encode requests with Big5 and responses with your platform's default encoding? Neither seems to be a likely candidate if you're talking to a mainframe.
    • Why do you use HTTP 1.0? The discussion referenced by the blog entry seems to be motivated by (broken) proxies. Unless you have that specific problem, using HTTP 1.0 may cause more trouble than do any good. 
    • You should properly dispose of request and response streams with using or try/finally blocks. If there is an exception in your code, you may leak resources. 
    Monday, January 08, 2007 4:35 PM
  • Why the call to HttpWebRequest.Abort()?
  • ==> Originally, i hope to dispose HttpWebRequest immediatedly . But i think that it's not correct.   so,  how can i close the HttpWebRequest in vs2003, when the request is complete??

  • Note that it's sufficient to set ServicePointManager.Expect100Continue once in your application (e.g. on startup).
  • =>ok , i have already kill this line.....thx

  • Why do you encode requests with Big5 and responses with your platform's default encoding? Neither seems to be a likely candidate if you're talking to a mainframe.
  • ==>sorry , my english is poor, i do not understand your question [ Neither seems to be a likely candidate if you're talking to a mainframe.]exactly. But i guess that you just want to talk to me about the communication between mainframe and client.....i have already set it to big5....

  • Why do you use HTTP 1.0? The discussion referenced by the blog entry seems to be motivated by (broken) proxies. Unless you have that specific problem, using HTTP 1.0 may cause more trouble than do any good. 
  • ==>At the begining, i have not set this line, but the connection problem still occur. So  i reference other website's artical,and then set this line to my code..

    unfortunately, it's not succesfully......the problem still exist..(so i can kill the line now) .

  • You should properly dispose of request and response streams with using or try/finally blocks. If there is an exception in your code, you may leak resources. 
  • => thanks your suggestion, but outer of this function i have try catch sentence to handle error, when main procedure call the sub-routine... but i thinks that it's not the problem about connection error....

    so, i still have no idea about my problem....[The underlying connection is excepted to keep alive  was closed by the server]......

    i have advise my code as following:

    public string callService(string postData){

                HttpWebRequest httpReq = null;
                HttpWebResponse httpResp = null;
                System.Uri httpURL = new Uri(url);
                httpReq = (HttpWebRequest)WebRequest.Create(httpURL);


                httpReq.Timeout = 1000000;
                httpReq.ReadWriteTimeout = 1000000;
                    httpReq.Method = "POST";
                    httpReq.KeepAlive = false;  // reference from other website

                    httpReq.ContentType = "application/x-www-form-urlencoded";
                    StreamWriter StreamWriter1 = new StreamWriter(httpReq.GetRequestStream(), System.Text.Encoding.GetEncoding("Big5"));
                    StreamWriter1.Write(postData);
                    StreamWriter1.Close();
                httpResp = (HttpWebResponse)httpReq.GetResponse();
                Stream respStream = httpResp.GetResponseStream();
                StreamReader reader = new StreamReader(respStream, System.Text.Encoding.GetEncoding("Big5"));
                string result = reader.ReadToEnd();
                httpResp.Close();

                httpReq = null;
                httpResp = null;
                return result;

    }

Sunday, January 21, 2007 4:01 PM
  • 1. HttpWebRequest is not an IDisposable, so there's no need to explicitly close such an object. You have to make sure though that you close the stream obtained from GetRequestStream(). HttpWebResponse on the other hand is an IDisposable and should be closed explicitly (see below).

    3. I was just wondering why you use two different character encodings (Big5 and Encoding.Default) for requests and responses. It's not wrong per se, but rather unusual.

    5. An outer try block isn't able to properly dispose/close a local variable like "reader" or "StreamWriter1" in your code. Your code in callService() should look like this:

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
    using(Stream requestStream = request.GetRequestStream())
    {
      // write to stream
    }
    using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
     
    {
      Stream responseStream = response.GetResponseStream()
      // read from stream
    }

    Do you connect to the host via a proxy?

    Tuesday, January 23, 2007 8:22 PM
  • Hello,jooss:

    I appreciated your response sincerely.

    i don't know HttpWebRequest is not an IDisposible...., thanks your direction.

    well, Actually, setting the different encoding in my code is my fault . thanks, (althought, i understand that It's not wrong per se..^_^)

    Ok, I am adivsing my code right now, and i will try to verify the function .

    Whatever thanks your pattient for me..

    Masculine , Truly Yours

    Saturday, February 10, 2007 2:02 AM
  • Dear Jooss,

    Sorry, i had already try to use your suggesstion.

    It's not work........

    Well, let me describe my enviroment of network.

    In my enviroment , i have separate it to three parts.

    Part 1.    MainFrame Server

    Part2.     Two servers for loadbalance  ( and one server for discriminating the two servers; therfore, here exist three servers in this part)

    Part3.     Client pc

    illustarte as following  :

                                                                     ------------->server 1 for loadbalance

    client pc   ---->    loadbalance Server                                                                ===============>   MainFrame Server

                                                                     ------------->server2 for loadbalnce

    Well, aspx program  is putting on server1 and server2.  While client pc request the aspx page in one of server1 or 2 , the aspx program will call MainFrame Server's program through http protocal. And then , MainFrame server will return the result to server1 or 2. 

    While server1 or 2 process sucessfully , it will return final html to client pc through loadbalance server.

    The above description is my senario.

    why the "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.;"
    still occur in my program....??????????????????

    can you give me other suggestion??? thanks ...

     

                                                   god bless you 

                                                                                 Masculine

     

     

    the code is as following :

    public string myFunction(string url, string postData)
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                HttpWebRequest request = null;
                System.Uri httpURL = new Uri(url);

                HttpRequestCachePolicy cache = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                HttpWebRequest.DefaultCachePolicy = cache;

     
                request = (HttpWebRequest)WebRequest.Create(httpURL);

                request.ProtocolVersion = HttpVersion.Version10;
                request.KeepAlive = false;
                request.ContentType = "application/x-www-form-urlencoded";

                   request.Method = "POST";
                    //-------------------------------block1----------------------------------
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        StreamWriter StreamWriter1 = new StreamWriter(requestStream, System.Text.Encoding.GetEncoding("Big5"));
                        StreamWriter1.Write(postData);
                        StreamWriter1.Close();
                        requestStream.Close();
                    }

                string result = string.Empty;
                //-------------------------------block2----------------------------------
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream respStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(respStream, System.Text.Encoding.GetEncoding("Big5"));
                    result = reader.ReadToEnd();
                    response.Close();
                }
                request = null;
                httpURL = null;
                return result;
            }

    Monday, February 12, 2007 1:11 AM
  • Does it work if you bypass the load balancers and access the mainframe directly?
    Monday, February 12, 2007 5:06 PM
  • Hi Daniel,

     

    Did anybody already supply the code? Thanks.

    Tuesday, April 24, 2007 9:19 PM
  • Hi guys,

     

    Verify if when you put the app at web server, your web reference URL its right and your web.config.

     

    Regards,

     

    www.tritech.com.br

     

    Thursday, May 24, 2007 2:32 PM
  • Just a thought here guys. I was having this exact problem today, and did some searching and found this thread. Apparrently, a broken web.config file will also cause this problem. Broken, as in, forget to close a tag, or had an errant string of text in it. I'm still in the habit of manually editting my web.config files. Once I got all the syntax right in my config file, problem went away.
    Wednesday, May 30, 2007 11:30 PM
  • My client is getting "The underlying connection was closed. An expected error occurred on a receive" error on web farm.

    In an isolated server this error is not occurring. I am setting following properties of HTTPWebRequest object.

     

    requestor.Method = "POST"

    requestor.ProtocolVersion = HttpVersion.Version10

    requestor.ContentType = "text/xml-SOAP"

    requestor.KeepAlive = False

     

    This is .NET 1.1 application and is multi-threaded. I have come across different post suggesting setting DefaultConnectionLimit on ServicePointManager or setting Expect100Continue = False.

     

    Anyone encountered this issue or ideas on how to fix this?

     

    Thanks in advance.

    Sachin

    Friday, July 20, 2007 9:55 PM
  • Hi Sachin,

     

    I am experiencing the same error. Can you help me how did you solve this ?

     

    Thanks

     

    Tuesday, September 04, 2007 2:43 PM
  • Guys, I have been having the same problem posting data to an internal Apache web server. I used SSIS Script task to send and received data. I am pretty new to .NET. I get "The script threw an exception: The underlying connection was closed: The connection was closed unexpectedly.". Below is my code

     

     

    Function SendReceiveData(ByVal url As String) As String

    'Send data to Lola and receive a response.

    'Using HttpWebRequest , HttpWebResponse object to send and receive information.

    strPost = queryString

    'MsgBox(strPost)

    System.Net.ServicePointManager.Expect100Continue = False

    Dim objRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)

    objRequest.Method = "POST"

    objRequest.ContentLength = strPost.Length

    objRequest.ContentType = "application/x-www-form-urlencoded"

    objRequest.Timeout = 1200000

    objRequest.KeepAlive = False

    objRequest.ProtocolVersion = HttpVersion.Version10

     

    Try

    myWriter = New StreamWriter(objRequest.GetRequestStream())

    myWriter.Write(strPost)

    Catch ex As Exception

    Return ex.Message

    Finally

    myWriter.Flush()

    myWriter.Close()

    End Try

     

    Dim objResponse As HttpWebResponse = CType(objRequest.GetResponse(), HttpWebResponse)

    Dim sr As StreamReader

    sr = New StreamReader(objResponse.GetResponseStream())

    result = sr.ReadToEnd()

    'MsgBox(result)

    sr.Close()

    objResponse.Close()

    'MsgBox(result)

    'Return result

    End Function

    Function CheckForUpdate(ByVal returnedResult As String) As String

    Dim r As Int32

    'Parse the Response recived.

    'If the result received is a failure message then update the NewJacketNumber with the Failure message

    r = result.IndexOf("Fail")

    If r > 0 Then

    'Code the logic for Failure

    NewJacketNumber = result

    Else

    'If the result recieved is a success then parse the response to extract the new jacket number.

    'Code the logic for success

    NewJacketNumber = (result.Replace("SUCCESS", "")).Trim

    End If

    End Function

    Thursday, September 06, 2007 6:12 PM
  •  SachinChavan.in wrote:
    Dear Jörg Jooss And All

    cut...


    For same request above I tried several times and I use to get a proper response from the server few times.


    So the solution for the above that worked for me was

        System.Net.ServicePointManager.Expect100Continue = False

    So .Net is not asking for expect continue hence server is waiting to receive the complete data and is responding back with the response.


    Please let me know if above information finds ok for you all. If any modification or clarification required please feel free to bother me.

     

     

    This worked for me, thanks, very good post.

     

    I did also try setting the

    System.Net.HttpWebRequest.DefaultCachePolicy to NoCache as suggested in another post but this didnt help me.

     

    Adam

     

    Tuesday, December 11, 2007 12:55 PM
  • I solved this problem with my web services by calling Discover() method:

    YourWebService ws = new  YourWebService ();
    ws.Discover();

    just before calling the service webmethods
    Wednesday, February 06, 2008 11:29 AM
  •  

    When there is conflicting DataMember parameter, it will cause an error to occur during serialization and the process will stop. 

     

    For example.

     

    [DataContract]

    public class FooBar

    { ...

     

    [DataMember(Name="Name", Order=0,IsRequired=true,EmitDefaultValue = false )

      public string Name

        {

    get{return fooName;}

    set{fooName = value;}

         }

     

    ...}

     

    This causes a serialization problem, because this data member is required and the EmitDefaultValue(default value) is set to false. This is a conflict of setting.

     

    To correct the problem, set IsRequired to false or EmitDefaultValue to true or make sure that the two settings do not conflict.

     

    Hope this helps.

    Friday, February 15, 2008 12:05 AM
  • You should try to set webRequest.KeepAlive = false; this has work for me. For more details how to solve The underlying connection was closed.
    Tuesday, March 24, 2009 5:10 AM
  •  .NET Developer wrote:

    I think I figured out what the problem is, but I haven't found a good solution for it.

    In my code:

    webservice.MyWS ws1 = new webservice.MyWS();
    try
    {
         ws1.Get();
    }
    catch(Exception ex)
    {
         System.Diagnostics.Debug.Writeline(ex.Message);
    }

     

    It seems that an exception is thrown when the web service isn't ready.  So by retrying the webmethod, it eventually works.

    webservice.MyWS ws1 = new webservice.MyWS();
    int i = 0;
    Retry:
    try
    {
         ws1.Get();
    }
    catch(Exception ex)

         System.Diagnostics.Debug.Writeline(ex.Message);
         if (i < 3)
         {
              i++;
              goto Retry;
         }
    }

    Is there a way to check to see whether the webservice is ready?  And or wait for it to initialize?

     

     

     

    just one thing:  goto??

    I'd do a while loop like this:

    TryCount =0;
    Ready=False;

    While ( ! Ready && TryCount < 5){

    bool flag=false;
      try {

    ws.get()

      }
      catch{
           flag=true;

      }

    TryCount++;

    if (flag){

    //  stuff here

    }
    else{

    Ready=True;

    }
    }

    if ( !Ready && TryCount>4){
    //  throw something
    }

     

    a bit more logic there but I think that gives a clear flow of

    "If at first you don't sucseed Try Try Again"

    and a final  Throw for total failure cases.

    What about this:

    webservice.MyWS ws1 = new webservice.MyWS();
    for(int i = 0; i<3; i++) {
      try
     {
         ws1.Get();
         break;
      }
      catch(Exception ex)
      { 
         System.Diagnostics.Debug.Writeline(ex.Message);
      }
    }


     

    Monday, August 30, 2010 4:13 PM
  • How do I fix this error though? I put as you suggested HTTPRuntime block in my web.config. Still get this error. How do I open the connection back. ??? The underlying connection was closed: The connection was closed unexpectedly.
    Thursday, October 21, 2010 1:50 PM
  • Hi,

    Various solutions given in this article and other, unfortunately, didn't work for me. I tried both ServicePointManager.Expect100Continue and HttpWebRequest.KeepAlive on server and well as on client but didn't bear any fruit for me. I am using .NET Framework 3.5 at both server and client. Currently web service is asmx. I thought of moving it to WCF architecture but still I see lot of people complaining about this in WCF services as well. My client application runs on more than 300 locations in USA and few of them face this issue. Still these few are really a headache for me. I am so dishearten now.

    Between I came across some posts on various forums that tells that this problem can be due to the client being on Small Business Server or behind a proxy server. How much true is this?

    I would be really grateful to anyone providing help in this regard.

     

    Regards,

    Syed Tahami

    Monday, February 14, 2011 9:41 AM
  • I have some Enums as datamembers of my 'response class' that is returned by a method of my service. When this property is returned without any value, this exception is thrown (The underlying connection was closed: The connection was closed unexpectedly).

            [DataMember]
            public CurrencyTypeEnum CurrencyType { getset; }

    I have fixed this adding a nullable modifier like this:

            [DataMember]
            public CurrencyTypeEnum? CurrencyType { getset; }

    This was a particular problem but maybe can help in some cases.

    Thanks.

    Wednesday, August 17, 2011 1:35 PM
  • For me the cause was the result of returning an unknown object or the the returning object contained an unknown object.  By placing the KnownType attribute on the returning object resolved the issue for me.

    Also, to find the offending object, I turned on WCF message tracing.  This is what led us to the error.

    Friday, September 23, 2011 5:43 PM