Unexpected end of file from server

I wrote some simple code in Java, the method should connect to the website and return the BufferedReader.

When I use it on my PC, it works fine but when I put .jar file on the server I get this error:

Problem is quite strange because the exception isn’t thrown each time, sometimes everything is OK and program works fine.

Has anybody got any ideas?

7 Answers 7

"Unexpected end of file" implies that the remote server accepted and closed the connection without sending a response. It’s possible that the remote system is too busy to handle the request, or that there’s a network bug that randomly drops connections.

With the information available it’s impossible to say what’s going wrong. If you have access to the servers in question you can use packet sniffing tools to find what exactly is sent and received, and look at logs to of the server process to see if there are any error messages.

This exception is encountered when you are expecting a response, but the socket has been abruptly closed.

Java’s HTTPClient , found here, throws a SocketException with message "Unexpected end of file from server" in a very specific circumstance.

After making a request, HTTPClient gets an InputStream tied to the socket associated with the request. It then polls that InputStream repeatedly until it either:

  1. Finds the string "HTTP/1."
  2. The end of the InputStream is reached before 8 characters are read
  3. Finds a string other than "HTTP/1."

In case of number 2, HTTPClient will throw this SocketException if any of the following are true:

  • The HTTP method is CONNECT
  • The HTTP method is POST and the client is set to streaming mode
Читайте также:  Elan input device что это

Why would this happen

This indicates that the TCP socket has been closed before the server was able to send a response. This could happen for any number of reasons, but some possibilities are:

  • Network connection was lost
  • The server decided to close the connection
  • Something in between the client and the server (nginx, router, etc) terminated the request

Note: When Nginx reloads its config, it forcefully closes any in-flight HTTP Keep-Alive connections (even POSTs), causing this exact error.

I am preparing an interim release of a client project and am encountering an exception when JWS processes the jnlp file. The sequence of events is as follows:

I request a .jsp page which displays a form. The action of the form is defined as " /app/filename.jnlp" and the method as "get". I select the submit button for the form. The .jnlp file is downloaded and JWS is invoked to open it. A "Download Error" dialog box is displayed with the message "Unable to Launch Application". Selecting the "Details" button of this dialog displays four tabs "General", "Launch File", "Exception", and "Wrapped Exception".

General:
An error occurred while launching/running the application.

Title: Application Name
Vendor: Vendor name
Category: Download Error

Unable to load resource: http://host/NASApp/webapp_name/app/filename.jnlp

Launch File:
The entire launch file is displayed and is as expected.

Exception:
JNLPException[category: Download Error : Exception: java.net.SocketException: Unexpected end of file from server : LaunchDesc: null ]
at com.sun.javaws.cache.DownloadProtocol.doDownload(Unknown Source)
at com.sun.javaws.cache.DownloadProtocol.isLaunchFileUpdateAvailable(Unknown Source)
at com.sun.javaws.LaunchDownload.getUpdatedLaunchDesc(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source)
at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Wrapped Exception:
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.sun.javaws.util.URLUtil.doesURLExist(Unknown Source)
at com.sun.javaws.cache.DownloadProtocol.doDownload(Unknown Source)
at com.sun.javaws.cache.DownloadProtocol.isLaunchFileUpdateAvailable(Unknown Source)
at com.sun.javaws.LaunchDownload.getUpdatedLaunchDesc(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source)
at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Читайте также:  Edb execute disable bit в биосе

The environment is iPlanet App server 6.0 on Windows NT with IIS acting as the webserver. I’ve tried this with both IE and Netscape 6.2.1.

Я написал простой код в Java, метод должен подключиться к веб-сайту и вернуть BufferedReader.

Когда я использую его на своем ПК, он работает нормально, но когда я помещаю файл .jar на сервер, я получаю эту ошибку:

Проблема довольно странная, потому что исключение не вызывается каждый раз, иногда все в порядке, и программа работает нормально.

Есть ли у кого-нибудь идеи?

"Неожиданный конец файла" означает, что удаленный сервер принял и закрыл соединение без отправки ответа. Возможно, удаленная система слишком занята, чтобы обрабатывать запрос, или что существует сетевая ошибка, которая случайно отключает соединения.

С доступной информацией невозможно сказать, что происходит не так. Если у вас есть доступ к указанным серверам, вы можете использовать инструменты поиска пакетов, чтобы найти то, что точно отправлено и получено, и посмотреть журналы на серверный процесс, чтобы увидеть, есть ли сообщения об ошибках.

Это исключение встречается, когда вы ожидаете ответа, но сокет был внезапно закрыт.

Java HTTPClient , найденный здесь, выдает сообщение SocketException с сообщением "Неожиданный конец файла с сервера" в очень специфических обстоятельствах.

После выполнения запроса HTTPClient получает привязку InputStream к сокету, связанному с запросом. Затем он проверяет, что InputStream несколько раз, пока он не будет:

  • Находит строку "HTTP/1."
  • Конец InputStream достигается до чтения 8 символов.
  • Находит строку, отличную от "HTTP/1."

В случае номера 2 HTTPClient будет выбрасывать этот SocketException , если выполняется одно из следующих условий:

  • Метод HTTP CONNECT
  • HTTP-метод POST , и клиент настроен на режим потоковой передачи
Читайте также:  Intel hd graphics 6000 тест в играх

Почему это произойдет

Это означает, что сокет TCP был закрыт до того, как сервер смог отправить ответ. Это может произойти по ряду причин, но некоторые возможности:

  • Сетевое соединение было потеряно
  • Сервер решил закрыть соединение
  • Что-то между клиентом и сервером (nginx, router и т.д.) завершило запрос

Примечание. Когда Nginx перезагружает свою конфигурацию, он принудительно закрывает любые HTTP-соединения Keep-Alive в прямом эфире (даже POST) вызвав эту точную ошибку.

Rate this post

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *