Java net sockettimeoutexception read timed out ошибка

I have a Tomcat based web application. I am intermittently getting the following exception, Caused by: java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(...

I have a Tomcat based web application. I am intermittently getting the following exception,

Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:532)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:501)
    at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:563)
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:124)
    at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:346)
    at org.apache.coyote.Request.doRead(Request.java:422)
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:290)
    at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:431)
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:315)
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:200)
    at java.nio.channels.Channels$ReadableByteChannelImpl.read(Channels.java:385)

Unfortunately I don’t have access to the client, so I am just trying to confirm on various reasons this can happen,

  1. Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be Tomcat connector → connectionTimeout attribute.

  2. Client has a read timeout set, and server is taking longer than that to respond.

  3. One of the threads I went through, said this can happen with high concurrency and if the keepalive is enabled.

For #1, the initial value I had set was 20 sec, I have bumped this up to 60sec, will test, and see if there are any changes.

Meanwhile, if any of you guys can provide you expert opinion on this, that’l be really helpful. Or for that matter any other reason you can think of which might cause this issue.

double-beep's user avatar

double-beep

4,85916 gold badges32 silver badges41 bronze badges

asked Jun 13, 2013 at 4:30

Victor's user avatar

1

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn’t sending. You don’t need to worry about it. Browser clients come and go in all sorts of strange ways.

answered Jun 13, 2013 at 5:45

user207421's user avatar

6

Here are the basic instructions:-

  1. Locate the «server.xml» file in the «conf» folder beneath Tomcat’s base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out — this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased — e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds — if this is insufficient, the property may need to be added.
  5. Restart Tomcat

answered Sep 19, 2018 at 13:10

Steve Chambers's user avatar

Steve ChambersSteve Chambers

35.5k21 gold badges151 silver badges203 bronze badges

Connection.Response resp = Jsoup.connect(url) //
                .timeout(20000) //
                .method(Connection.Method.GET) //
                .execute();

actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.

answered Mar 5, 2019 at 15:09

Rishabh Gupta's user avatar

1

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

answered Dec 4, 2020 at 17:23

Anand Kumar's user avatar

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works.
If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

answered Jan 31, 2021 at 13:38

Morkus's user avatar

MorkusMorkus

4876 silver badges19 bronze badges

1

This happenned to my application, actually I was using a single Object which was being called by multiple functions and those were not thread safe.

Something like this :

Class A{
    Object B;
    function1(){
        B.doSomething();
    }
    function2(){
        B.doSomething();
    }
}

As they were not threadsafe, I was getting these errors :

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Socket is closed

and

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out

This is how I fixed it :

Class A{
    function1(){
        Object B;
        B.doSomething();
    }
    function2(){    
        Object B;
        B.doSomething();
    }
}

Hope it helps

answered Jun 22, 2022 at 10:27

Aditya's user avatar

It means time out from your server response. It causes due to server config and internet response.

answered Mar 20, 2021 at 15:32

jawad zahoor's user avatar

I am using 11.2 and received timeouts.

I resolved by using the version of jsoup below.

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <scope>compile</scope>
    </dependency>

entpnerd's user avatar

entpnerd

9,6897 gold badges44 silver badges67 bronze badges

answered Feb 7, 2018 at 14:40

Shahid Hussain Abbasi's user avatar

I have a Tomcat based web application. I am intermittently getting the following exception,

Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:532)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:501)
    at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:563)
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:124)
    at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:346)
    at org.apache.coyote.Request.doRead(Request.java:422)
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:290)
    at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:431)
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:315)
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:200)
    at java.nio.channels.Channels$ReadableByteChannelImpl.read(Channels.java:385)

Unfortunately I don’t have access to the client, so I am just trying to confirm on various reasons this can happen,

  1. Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be Tomcat connector → connectionTimeout attribute.

  2. Client has a read timeout set, and server is taking longer than that to respond.

  3. One of the threads I went through, said this can happen with high concurrency and if the keepalive is enabled.

For #1, the initial value I had set was 20 sec, I have bumped this up to 60sec, will test, and see if there are any changes.

Meanwhile, if any of you guys can provide you expert opinion on this, that’l be really helpful. Or for that matter any other reason you can think of which might cause this issue.

double-beep's user avatar

double-beep

4,85916 gold badges32 silver badges41 bronze badges

asked Jun 13, 2013 at 4:30

Victor's user avatar

1

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn’t sending. You don’t need to worry about it. Browser clients come and go in all sorts of strange ways.

answered Jun 13, 2013 at 5:45

user207421's user avatar

6

Here are the basic instructions:-

  1. Locate the «server.xml» file in the «conf» folder beneath Tomcat’s base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out — this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased — e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds — if this is insufficient, the property may need to be added.
  5. Restart Tomcat

answered Sep 19, 2018 at 13:10

Steve Chambers's user avatar

Steve ChambersSteve Chambers

35.5k21 gold badges151 silver badges203 bronze badges

Connection.Response resp = Jsoup.connect(url) //
                .timeout(20000) //
                .method(Connection.Method.GET) //
                .execute();

actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.

answered Mar 5, 2019 at 15:09

Rishabh Gupta's user avatar

1

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

answered Dec 4, 2020 at 17:23

Anand Kumar's user avatar

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works.
If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

answered Jan 31, 2021 at 13:38

Morkus's user avatar

MorkusMorkus

4876 silver badges19 bronze badges

1

This happenned to my application, actually I was using a single Object which was being called by multiple functions and those were not thread safe.

Something like this :

Class A{
    Object B;
    function1(){
        B.doSomething();
    }
    function2(){
        B.doSomething();
    }
}

As they were not threadsafe, I was getting these errors :

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Socket is closed

and

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out

This is how I fixed it :

Class A{
    function1(){
        Object B;
        B.doSomething();
    }
    function2(){    
        Object B;
        B.doSomething();
    }
}

Hope it helps

answered Jun 22, 2022 at 10:27

Aditya's user avatar

It means time out from your server response. It causes due to server config and internet response.

answered Mar 20, 2021 at 15:32

jawad zahoor's user avatar

I am using 11.2 and received timeouts.

I resolved by using the version of jsoup below.

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <scope>compile</scope>
    </dependency>

entpnerd's user avatar

entpnerd

9,6897 gold badges44 silver badges67 bronze badges

answered Feb 7, 2018 at 14:40

Shahid Hussain Abbasi's user avatar

Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.

Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

2017-10-03_153645.png

Полная печать исключения состоит из 3-х частей:

  1. Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
  2. Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
  3. Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).

Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.

В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).

При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.

org.lwjgl.LWJGLException: Pixel format not accelerated
Недоступно аппаратное ускорение графики. Описание ошибки (англ.)

Решение: Установите последнюю версию драйвера видеокарты.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.

Что можно сделать:

  • Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
  • Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.

java.net.SocketTimeOutException: Read timed out
Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.

Что можно сделать:

  • Отключите антивирус и попробуйте выполнить запрос снова.
  • Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
  • Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.

java.net.ConnectException: Connection timed out: connect
Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.

Что можно сделать:

  • Проверьте наличие подключения к интернету.
  • Временно отключите антивирус и Firewall.

java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.

java.lang.ClassCastException: XXX cannot be cast to YYY
Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.io.IOException: Server returned HTTP response code: 000 for URL
Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».

Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.

java.lang.UnsatisfiedLinkError: Can’t load library:
Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).

Что можно сделать:

  • Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
    Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.

java.lang.RuntimeException: Unknown character in
Синтаксическая ошибка в конфигурационном файле мода.

Что можно сделать:

  • Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
  • Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
  • Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.

java.lang.NullPointerException (NPE)
Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.net.UnknownHostException
Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).

Что можно сделать:

  • Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
  • Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.

java.io.EOFException: Unexpected end of ZLIB input stream
Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.

java.net.SocketException: Address family not supported by protocol family: connect
Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.

image.png

java.lang.OutOfMemoryError
А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:

  • Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
  • Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.

Hi All ,
I have webservice client connecting to SOAP Servivces through HTTPS using sun JSSE implementation. Everytime i make a webservice call i get the Read timed out exception. I am sure of SSL handshaking is happening. Below is the stack trace. I am behind the proxy as well.

Anything obivious wrong in here.
Thakns in advance.

AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.net.SocketTimeoutException: Read timed out
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.apache.axis.transport.http.HTTPSender.readHeadersFromSocket(HTTPSender.java:506)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:127)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:71)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:150)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:120)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:180)
at org.apache.axis.client.Call.invokeEngine(Call.java:2564)
at org.apache.axis.client.Call.invoke(Call.java:2553)
at org.apache.axis.client.Call.invoke(Call.java:2248)
at org.apache.axis.client.Call.invoke(Call.java:2171)
at org.apache.axis.client.Call.invoke(Call.java:1691)
at GetCLD.getCLD(GetCLD.java:110)
at GetCLD.main(GetCLD.java:145)

java.net.SocketTimeoutException: Read timed out
at org.apache.axis.AxisFault.makeFault(AxisFault.java:129)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:131)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:71)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:150)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:120)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:180)
at org.apache.axis.client.Call.invokeEngine(Call.java:2564)
at org.apache.axis.client.Call.invoke(Call.java:2553)
at org.apache.axis.client.Call.invoke(Call.java:2248)
at org.apache.axis.client.Call.invoke(Call.java:2171)
at org.apache.axis.client.Call.invoke(Call.java:1691)
at GetCLD.getCLD(GetCLD.java:110)
at GetCLD.main(GetCLD.java:145)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at org.apache.axis.transport.http.HTTPSender.readHeadersFromSocket(HTTPSender.java:506)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:127)
… 11 more
java.lang.NullPointerException
at ParseResult.getStatus(ParseResult.java:5)
at GetCLD.main(GetCLD.java:150)

Jsoup SocketTimeoutException read timed out, connect timed out example shows how to fix SocketTimeoutException while using Jsoup in Java. The example also shows how to set the timeout in Jsoup.

How to fix Jsoup java.net.SocketTimeoutException: Read timed out exception?

You may encounter “java.net.SocketTimeoutException: Read timed out” exception while using the Jsoup. Here is the program which gave me the exception.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

package com.javacodeexamples.libraries.jsoup;

import java.io.IOException;

import org.jsoup.Connection;

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

public class JsoupSocketTimeOutExample {

    public static void main(String[] args) {

        try{

            //connect to the website

            Connection connection = Jsoup.connect(«http://www.example.com»);

            //set user agent to Google Chrome

            connection.userAgent(«Mozilla/5.0»);

            //get the HTML document

            Document doc = connection.get();

            //parse text from HTML

            String strHTML = doc.text();

        }catch(IOException ioe){

            //System.out.println(«IOException: » + ioe);

            ioe.printStackTrace();

        }

    }

}

Output

java.net.SocketTimeoutException: Read timed out

    at java.net.SocketInputStream.socketRead0(Native Method)

    at java.net.SocketInputStream.read(Unknown Source)

    at java.net.SocketInputStream.read(Unknown Source)

    at sun.security.ssl.InputRecord.readFully(Unknown Source)

    …

Fix: 

The problem is the default Jsoup timeout which is 3 seconds. If you encounter the exception “java.net.SocketTimeoutException: Read timed out”, it means that time our program took to read the requested webpage was exceeded the default timeout time (3 seconds).

You need to increase the timeout Jsoup uses to fix the problem using timeout method of Connection class.

Connection timeout(int timeout)

This method sets the connect and read timeout both. Please note that the timeout is in milliseconds.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

try{

    //connect to the website

    Connection connection = Jsoup.connect(«http://www.example.com»);

    //set user agent to Google Chrome

    connection.userAgent(«Mozilla/5.0»);

    //set timeout to 10 seconds

    connection.timeout(10 * 1000);

    //get the HTML document

    Document doc = connection.get();

    //parse text from HTML

    String strHTML = doc.text();

}catch(IOException ioe){

    //System.out.println(«IOException: » + ioe);

    ioe.printStackTrace();

}

How to fix Jsoup java.net.SocketTimeoutException: Connect timed out exception?

Another exception Jsoup may throw is “java.net.SocketTimeoutException: Connect timed out”. This exception means the time taken by our program to connect to the requested URL exceeded the timeout Jsoup uses.

Here is how to fix/resolve the “Connect time out” exception.

1) Make sure you are connected to the internet. Try to open the same URL in the browser and see if it opens the page.
2) Specify Jsoup connection time out before getting the document as given below.

String strText =

        Jsoup

        .connect(«http://www.example.com/»)

        .userAgent(«Mozilla/5.0»)

        .timeout(10 * 1000)

        .get()

        .text();

3) Are you behind the proxy? If yes, set Jsoup proxy.
4) It is always best practice to set user agent and referrer while creating a Jsoup connection.

Many times setting property user agent and referrer values solves this problem.

This example is a part of the Jsoup tutorial with examples.

Please let me know your views in the comments section below.

About the author

  • Author
  • Recent Posts

Rahim

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

We are on YouTube!

The idea is to make the server listening and the clients would connect to them.
But not as a Modbus TCP client, as a normal TCP client, so the server could read the clients (act like Modbus Master) rather than read by clients.
Maybe the idea totally wrong.

The test code:

    @Test
    public void testConnection() throws IOException, ModbusNumberException, ModbusProtocolException, ModbusIOException {
        ServerSocket serverSocket = new ServerSocket(3333);
        Socket client = serverSocket.accept();
        ModbusTranslator modbusTranslator = new ModbusTranslator(client);
        modbusTranslator.connect();
        modbusTranslator.setResponseTimeout(3000);
        modbusTranslator.writeSingleRegister(1,1,1);
    }

Which will issue a SocketTimeoutException when running the test.
Using hercules-setup-utility from https://www.hw-group.com/software/hercules-setup-utility
to simulate a client socket.

  1. The network is fine when using client.getOutputStream() and client.getInputStream();
  2. The error log is almost same if change last line to modbusTranslator.readHoldingRegisters(1,1,1);
  3. The ModbusTranslator implements FrameEventListenerList with a custom EmbeddedConnection which extends ModbusConnection

The mainly different from your ModbusMasterConnection is it get the socket instead from init from tcp parameters.

    @Override
    protected void openImpl() {
        if (!isOpened()) {
            if (socket.isConnected()) {
                try {
                    transport = ModbusTransportFactory.createTCP(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                setReadTimeout(getReadTimeout());
            }
        }
    }
com.intelligt.modbus.jlibmodbus.exception.ModbusIOException: java.net.SocketTimeoutException: Read timed out

	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:103)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportTCP.read(ModbusTransportTCP.java:50)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at dems.server.ModbusTranslator.readResponse(ModbusTranslator.java:80)
	at dems.server.ModbusTranslator.processRequest(ModbusTranslator.java:100)
	at dems.server.ModbusTranslator.writeSingleRegister(ModbusTranslator.java:264)
	at dems.server.ModbusTranslatorTest.testConnection(ModbusTranslatorTest.java:19)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.net.SocketTimeoutException: Read timed out
	at java.base/java.net.SocketInputStream.socketRead0(Native Method)
	at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
	at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:345)
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamTCP$1.read(InputStreamTCP.java:55)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.LoggingInputStream.read(LoggingInputStream.java:61)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.ModbusInputStream.read(ModbusInputStream.java:50)
	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:91)
	... 29 more

Disconnected from the target VM, address: '127.0.0.1:53170', transport: 'socket'

Process finished with exit code -1

Any help would be appreciated.

Понравилась статья? Поделить с друзьями:
  • Java net socketexception network is unreachable как исправить
  • Java net socketexception connection reset by peer socket write error
  • Java lang unsatisfiedlinkerror как исправить андроид
  • Java lang stackoverflowerror как исправить
  • Java lang securityexception ошибка как исправить на андроид