Java connected time out

How to handle java.net.SocketTimeoutException

Your Java socket is timing out (throws java.net.SocketTimeoutException: Connection timed out) means that it takes too long to get respond from other device and your request expires before getting response.

How to solve?

A developer can pre-set the timeout option for both client and server operations.

From Client side:

You can effectively handle it from client side by define a connection timeout and later handle it by using a try/catch/finally block. You can use the connect(SocketAddress endpoint, int timeout) method and set the timeout parameter:

Socket socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(host, port); socket.connect(socketAddress, 12000); //12000 are milli seconds

Note: If the timeout elapses before the method returns, it will throw a SocketTimeoutException.

If you are using OkHttp Client then you can add:

OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(60, TimeUnit.SECONDS); client.setReadTimeout(60, TimeUnit.SECONDS); client.setWriteTimeout(60, TimeUnit.SECONDS);

If you are using OkHttp3 then you must do it using the builder:

OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(60, TimeUnit.SECONDS); builder.readTimeout(60, TimeUnit.SECONDS); builder.writeTimeout(60, TimeUnit.SECONDS); client = builder.build();

Using try/catch/finally

If you are a developer, so you can surround the socket connection part of your code in a try/catch/finally and handle the error in the catch. You might try connecting a second time, or try connecting to another possible socket, or simply exit the program cleanly.

From Server side:

From server side you can use the setSoTimeout(int timeout) method to set a timeout value. The timeout value defines how long the ServerSocket.accept() method will block:

How to Java SocketTimeoutException?

How do I resolve a java.net.SocketTimeoutException

A socket is one end-point of a logical link between two computer applications. In order to establish a connection to the server from the remote client, the socket constructor is invoked, which instantiates a socket object. This operation blocks all other processes until a successful connection is made. However, if the connection isn’t successful after a period of time, the program throws a ConnectionException with a message:

This exception is occurring on following condition.

  1. Server is slow and default timeout is less, so just put timeout value according to you.
  2. Server is working fine but timeout value is for less time. so change the timeout value.

It is important to note that after this exception is thrown the socket remains valid , so you can retry the blocking call or do whatever you want with the valid socket.

So to avoid this exception in another way, you should keep the connection be alive using the method Socket.setKeepAlive() method although possibly you have not used the method setTimeout() , meaning asking the socket to unlimited block to receive.

Источник

Java.net.ConnectException: Connection timed out: no further information — Решение

При попытке подключения к серверу «Майнкрафт» пользователь может столкнуться с сообщением «Java.net.ConnectException: Connection timed out: no further information». Появление данного сообщения обычно сигнализирует о возникновении различного рода сетевых проблем при получении доступа к игровому серверу, из-за чего желание пользователя насладиться игровыми мирами «Майнкрафт» остаётся нереализованным. Ниже я разберу суть данной дисфункции, опишу её причины, а также поясню, как исправить ошибку Java.net.ConnEctexception на вашем ПК.

Сообщение Java.net.ConnectException

Connection timed out: no further information – особенности дисфункции

В переводе текст данного сообщения выглядит примерно как «Сетевой сбой Java. Время соединения истекло: дальнейшая информация отсутствует».

Указанная ошибка Java.net.ConnectException обычно возникает во время подключения к серверу игры «Майнкрафт», но также фиксировались спорадические случаи появления данной ошибки при работе других продуктов, использующих «Java» (к примеру, на «Azure notification hub»).

Появление проблемы «Java.net.ConnectException: Connection timed out: no further information» имеет следующие причины:

  • Пользователь использует нестабильное сетевое соединение с медленным интернетом;
  • На ПК пользователя установлена устаревшая версия «Java»;
  • Пользователь пользуется устаревшей версией «Майнкрафт»;
  • Наблюдаются сбои в работе игрового сервера, к которому пробует подключиться пользователь (ресурс не доступен, проходят технические работы и др.);
  • Антивирус или брандмауэр блокирует подключения к игровому серверу;
  • Пользователь использует динамический IP;
  • Пользовательский роутер работает некорректно.

Как исправить «Java.net.ConnectException: Connection timed out»

Существуют несколько способов избавиться от ошибки Java.net.ConnectException. Рассмотрим их по порядку:

  • Перезагрузите ваш PC. В некоторых случаях данный простой метод позволял решить ошибку java.net.connectexception connection refused;
  • Установите на ПК свежую версию «Java». Довольно частой причиной рассматриваемой проблемы является устаревшая версия «Java» на пользовательском ПК. Перейдите в Панель управления, затем в «Программы», там найдите «Java» и кликните на неё. После появления окна её настроек перейдите на вкладку «Update», нажмите там на кнопку «Update Now», и установите в системе требуемые обновления.

Данную процедуру необходимо провести как на вашей машине, так и на машине того пользователя, с которым вы собираетесь играть в «Майнкрафт» по сети;

Кнопка

Опция разрешения взаимодействия

    Внесите «Майнкрафт» в исключения брандмауэра и антивируса на вашем ПК. Запустите Панель управления, перейдите в «Система и безопасность», там найдите «Брандмауэр Виндовс» и кликните на него. В открывшемся окне настроек брандмауэра слева сверху выберите опцию «Разрешения взаимодействия…».

Картинка MINECRAFT

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

  • Попробуйте альтернативный сервер. Если подключения к конкретному серверу невозможно, тогда вполне вероятно, что у него наблюдаются временные проблемы в работе. Рекомендую попробовать альтернативный сервер, или подождать некоторое время, пока работоспособность начального сервера восстановиться;
  • Создайте сервер на другой машине. Если вы создаёте сервер, к которому подключается другой знакомый вам пользователь, тогда рекомендуется поменять базовый компьютер для создания сервера. То есть сервер должен создать уже другой пользователь, а вы подключитесь к нему. Часто это позволяло решить проблему net.ConnectException на пользовательском компьютере;
  • Используйте статистический IP-адрес. Если у вас есть возможность, рекомендуется использовать официальный (белый) IP-адрес, полученный через провайдера (обычно данная услуга имеет платный характер);
  • Установите на ваш ПК (гаджет) свежую версию «

    Заключение

    Наиболее распространёнными причинами ошибки «Java.net.ConnectException: Connection timed out: no further information» является устаревание пользовательской версии «Java» и блокировка брандмауэром подключения к нужному игровому серверу. Решением проблемы станет выполнение перечисленных выше советов, это позволит исправить ошибку Java.net.ConnectException на вашем ПК.

    Источник

    Java.Net.SocketTimeoutException: Connection Timed Out

    Java.Net.SocketTimeoutException: Connection Timed Out

    1. Sockets in Java
    2. Timeouts in Java
    3. Causes of java.net.SocketTimeoutException: Connection timed out in Java
    4. Solution to java.net.SocketTimeoutException: Connection timed out in Java

    In today’s article, we will discuss java.net.SocketTimeoutException: Connection timed out . But first, let’s take a closer look at the concepts of sockets and timeouts.

    Sockets in Java

    A logical link between two computer applications might have multiple endpoints, one of which is a socket.

    To put it another way, it is a logical interface that applications use to transmit and receive data over a network. An IP address and a port number comprise a socket in its most basic form.

    A unique port number is allotted to each socket, which is utilized to identify the service. Connection-based services use stream sockets that are based on TCP.

    Because of this, Java offers the java.net.Socket class as a client-side programming option.

    On the other hand, the java.net.ServerSocket class is utilized in server-side TCP/IP programming. The datagram socket based on UDP is another kind of socket, and it’s the one that’s employed for connectionless services.

    Java supports java.net.DatagramSocket for UDP operations.

    Timeouts in Java

    An instance of a socket object is created when the socket constructor is called, allowing a connection between the client and the server from the client side.

    As input, the constructor expects to receive the address of the remote host and the port number. After that, it tries to use the parameters provided to establish a connection to the remote host.

    The operation will prevent other processes from proceeding until a successful connection is created. But, the application will throw the following error if the connection is not successful after a specified time.

    java.net.SocketTimeoutException: Connection timed out 

    Listening to incoming connection requests, the ServerSocket class on the server side is permanently active. When a connection request is received by ServerSocket , the accept function is invoked to create a new socket object.

    Similar to the previous method, this one blocks until the remote client is connected.

    Causes of java.net.SocketTimeoutException: Connection timed out in Java

    1. The server is operating fine. However, the timeout value is set for a shorter time. Therefore, increase the value of the timeout .
    2. On the remote host, the specified port is not being listened to by any services.
    3. There is no route to the remote host being sent.
    4. The remote host does not appear to be allowing any connections.
    5. There is a problem reaching the remote host.
    6. Internet connection that is either slow or unavailable.

    Solution to java.net.SocketTimeoutException: Connection timed out in Java

    On the client side, the first thing we’ll do is construct a null socket . Following that, we will use the connect() method and then configure the timeout parameter where the timeout should be larger than 0 milliseconds.

    If the timeout expires before the function returns, SocketTimeoutException is thrown.

    Socket s = new Socket(); SocketAddress sAdres = new InetSocketAddress(host, port); s.connect(sAdres, 50000); 

    If you want to set a timeout value from the server side, you can use the setSoTimeout() function. The value of the timeout parameter determines the length of time that the ServerSocket.accept() function will block.

    ServerSocket servers = new new ServerSocket(port); servers.setSoTimeout(10000); 

    Similarly, the timeout should be more than 0 milliseconds. If the timeout expires before the method returns, the method will generate a SocketTimeoutException .

    Determining a connection timeout and then handling it afterward using a try-catch block is yet another excellent technique to deal with HttpException .

    HttpUrlConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(8000); 

    I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I’m a senior in an undergraduate program for a bachelor’s degree in Information Technology.

    Related Article — Java Error

    Источник

    Читайте также:  Python разработчик зарплата начинающего
  • Оцените статью