11 Replies Latest reply: May 12, 2007 10:26 PM by EJP RSS

    java.net.SocketException: Unexpected end of file from server

    807596
      Dear everyone,

      Could some one please explain what this exception is:
      java.net.SocketException: Unexpected end of file from server

      Why is this exception thrown and how I could avoid it?
      I get this exception from calling HttpUrlConnection.getResponseCode().

      Thanks a lot!
      George
        • 1. Re: java.net.SocketException: Unexpected end of file from server
          807596
          Dear everyone,

          Could some one please explain what this exception is:
          java.net.SocketException: Unexpected end of file from
          server

          Why is this exception thrown and how I could avoid
          it?
          I get this exception from calling
          HttpUrlConnection.getResponseCode().

          Thanks a lot!
          George
          It would help to see a stack dump of the actual process or the code-base. If you include the code-base, make sure and show where you open,use and close the HttpUrlConnection object. I'm betting that you have corrupted the HttpUrlConnection object. Either that or the Server-side's OutputStream has already been flushed. It's pure guess work without seeing the code in context....

          • 2. Re: java.net.SocketException: Unexpected end of file from server
            807596
            Here are some excerpts from my codes. As I have
            mentioned b4, I get the SocketException when I
            attempt to get the response code.

            At the server-side:
                  // get the reader and writer streams for this socket.
                  final DataOutputStream writer = new DataOutputStream(
                                                     new BufferedOutputStream(
                                                         clientSocket.getOutputStream()));
                  final BufferedReader read = new BufferedReader
                                (new InputStreamReader(clientSocket.getInputStream()));
            
                  // read from the stream and process the request.
                  String inMsg;
                  while (!"".equals(read.readLine()))
                  {
                  }
                  // the message after the blank line is the actual msg!
                  inMsg = read.readLine();
            
                  // process the message and send a response...
            
                     // first write the HTTP response.
                     writer.writeBytes(httpResponse);
                     // next write the length of this message as an integer.
                     writer.writeInt(msg.length());
            
                     // then send the message itself.
                     if (transceiver.DEBUG) System.out.println(msg);
                     writer.writeBytes(msg);
            
                     // don't forget to flush and close the socket.
                     writer.flush();
                     writer.close();
            Now at the client side: (httpConn is an instance of a
            wrapper class of HttpURLConnection.)
                  // now get the writer stream - so as to send the message.
                  PrintStream writer = httpConn.getWriterStream();
            
                  // send message.
                  writer.println(msg);
            
                  // I must close the writer, too. Otherwise nothing gets sent.
                  writer.close();
            
                  // check the response code from server.
                  int respCode = httpConn.getResponseCode();
                  // at least print an error if I am not getting HTTP_OK.
                  if (respCode != 200)
                  {
                     System.out.println("ERROR: Response code from server is not HTTP_OK");
                  }
            
                  // open reader stream.
                  DataInputStream reader = httpConn.getReaderStream();
            
                  // read from the server...
                  rThread.start();
            • 3. Re: java.net.SocketException: Unexpected end of file from server
              807596
              I am also getting this exception intermittently in a high-volume https client application. Here is some information about my setup.

              Platform: Sun Ultra 10
              OS: SunOS 5.8
              JRE: 1.4.1_01 with 64-bit extensions for Solaris
              API: HttpsUrlConnection

              Here is part of the stack trace.

              java.net.SocketException: Unexpected end of file from server
              at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:802)
              at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:702)
              at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:583)
              at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:238)
              at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(DashoA6275)
              ...

              Sorry, I don't have any fixes or workarounds. I hope someone else does.


              --Alex

              • 4. Re: java.net.SocketException: Unexpected end of file from server
                800384
                The error from HttpURLConnection.praseHeader() is really the problem here, though transparently it was caused in the higher-level object.


                Here are some possible reasons...

                1. The connection seems to have been dropped by the server.
                2. A non-suuported HTTP version or format was used.
                - HTTP 1.0 does not issue Status Lines that begin with "HTTP/1.1", so
                if you expect a different version and it is not there, then this would
                be an Exception (to the rule).
                3. Packets are being dropped without retransmission from the server.
                4. Non-Implemented Method (GET, HEAD, POST, TRACE, DELETE, PUT), if you
                expect to get a POST and in reality get a TRACE, then the line will be different and could possibly cause an error (but an exception?).
                5. A timeout or connection was reset.
                • 5. Re: java.net.SocketException: Unexpected end of file from server
                  807596
                  I'll have to rule out 2 and 4. If the request is repeated after getting the error, it is usually fine.

                  So it's something wrong with the connection... unfortunately, this error doesn't come up until AFTER I've sent the entity body of the POST request. I cannot afford to cache POST requests, so retrying the request is no longer an option at this point.

                  The JRE should throw an exception sooner. That, or it should try reconnecting on its own. I thought the point of HttpsURLConnection was to abstract away the details of making TCP connections?

                  --Alex                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                  • 6. Re: java.net.SocketException: Unexpected end of file from server
                    800384
                    It seems then that the vilian in this case is probably the server-side MIME-Type handler.

                    When you send your file, the server is interpreting the content by using MIME Types. If the server interprets the file as a different type (such as a video file when it is a text file) this would cause an error, that would be the unexpected EOF.

                    The server seems to be looking for some specific code in the file. But when the file ends without sending the expected code.
                    • 7. Re: java.net.SocketException: Unexpected end of file from server
                      800384
                      !!Corrections!!

                      Your server is not using the actual STATUS LINE as the response, you are looking for a blank line before it and then, skip past the first line with text and use the 2nd line with text to be the response.

                      HTTP uses (client-side request)

                      LINE 1: GET /files/cool/java_file_1.htm HTTP/1.1
                      LINE 2: ACCEPT-ENCODING: */*
                      LINE 3: CONTENT-TYPE: [...]

                      And so on and so forth, what you are doing on the server is thinking that LINE 1 is blank, which is incorrect, then the first line with text will cause your loop to break, then you read LINE 2 and take that as the response.

                      The client-side should see a (normal) response, if the file exists as...

                      LINE 1: HTTP/1.1 200 OK
                      LINE 2: CONTENT-TYPE: TEXT/HTML
                      LINE 3: CONTENT-ENCODING: ASCII
                      LINE 4: CACHE-CONTROL: NO CACHE
                      LINE 5: CONTENT-LENGTH: 4000
                      LINE 6: [CARRIAGE RETURN]
                      LINE 7: [LINE FEED]
                      LINE 8: <HTML>
                      ....
                      LINE N: </HTML>

                      Then the socket should close, or stay open if the Keep-Alive connection setting is used.
                      • 8. Re: java.net.SocketException: Unexpected end of file from server
                        807597
                        A possible solution is:
                        Socket s = new Socket(host, port);
                        
                        s.setKeepAlive( true );
                        
                        // The SoLinger Attribute is used to determine what to do when data is in 
                        // the socket's buffer when the socket is closed.
                        // If linger is set to true, then the close operation will block until the socket 
                        // buffers are empty, or the linger_time has expired.
                        
                        s.setSoLinger( true, 20 );
                        When the socket gets closed, it will wait for the internal buffer to be delivered to the receiver instead of closing immediately and possibly loosing data.

                        The SoLinger should be configured on the sending side.
                        • 9. Re: java.net.SocketException: Unexpected end of file from server
                          EJP
                          (a) This thread is four years old.

                          (b) TCP keepalive is not the same as HTTP keepalive.

                          (c) TCP 'linger' is 'true' by default, so a TCP close always delivers pending data by default. A TCP close only loses data if people fiddle with 'linger', which they should not do in 99.999999999999999999% of cases. Any time I see Socket.setSoLinger() in a Java program I immediately get really suspicious.

                          (e) None of this has anything to do with the original problem.

                          (f) You have crossposted this in at least two other places where it is also irrelevant.
                          • 10. Re: java.net.SocketException: Unexpected end of file from server
                            800351
                            c) TCP 'linger' is 'true' by default,
                            pp61, 3.16 of your Fundamental Networking in Java book says:
                            A return value of -1 from the getSoLinger method indicates the default setting (linger = false).

                            Which is correct?
                            • 11. Re: java.net.SocketException: Unexpected end of file from server
                              EJP
                              The book is correct. What I should have said here is that the action of TCP in continuing to flush pending output data is the default action. 'linger = true' causes close() to wait a bit while this happens, unless you also set the timeout to zero which causes an abortive close. linger=false caused the close to be asynchronous to the continued writing of pending data. So all the stuff in the above posting is pointless as well as not addressing the OP's problem.