VK API. Периодически возникает ошибка ReadTimeout: HTTPSConnectionPool(host=’api.vk.com’, port=443): Read timed out. (read timeout=10). Что делать?
-
Вопрос заданболее трёх лет назад
-
1521 просмотр
1. Introduction
In this tutorial, we’ll focus on the timeout exceptions of Java socket programming. Our goal is to understand why these exceptions occur, and how to handle them.
2. Java Sockets and Timeouts
A socket is one end-point of a logical link between two computer applications. In other words, it’s a logical interface that applications use to send and receive data over the network.
In general, a socket is a combination of an IP address and a port number. Each socket is assigned a specific port number that’s used to identify the service.
Connection-based services use TCP-based stream sockets. For this reason, Java provides the java.net.Socket class for client-side programming. Conversely, server-side TCP/IP programming makes use of the java.net.ServerSocket class.
Another type of socket is the UDP-based datagram socket, which is used for connectionless services. Java provides java.net.DatagramSocket for UDP operations. However, in this tutorial, we’ll focus on TCP/IP sockets.
3. Connection Timed Out
3.1. What Is “Connection Timed Out”?
For establishing a connection to the server from the client-side, the socket constructor is invoked, which instantiates a socket object. The constructor takes the remote host address and the port number as input arguments. After that, it attempts to establish a connection to the remote host based on the given parameters.
The operation blocks all other processes until a successful connection is made. However, if the connection isn’t successful after a certain time, the program throws a ConnectionException with a “Connection timed out” message:
java.net.ConnectException: Connection timed out: connect
From the server-side, the ServerSocket class continuously listens to incoming connection requests. When ServerSocket receives a connection request, it invokes the accept() method to instantiate a new socket object. Similarly, this method also blocks until it establishes a successful connection with the remote client.
If the TCP handshakes aren’t complete, the connection remains unsuccessful. As a result, the program throws an IOException indicating that an error occurred while establishing a new connection.
3.2. Why It Occurs?
There can be several reasons for a connection timeout error:
- No service is listening to the given port on the remote host
- The remote host isn’t accepting any connection
- The remote host isn’t available
- Slow internet connection
- No forwarding path to the remote host
3.3. How to Handle It?
Blocking times aren’t bounded, and a programmer can pre-set the timeout option for both client and server operations. For the client-side, we’ll first create an empty socket. After that, we’ll 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, 30000);
The timeout unit is in milliseconds and should be greater than 0. However, if the timeout expires before the method call returns, it will throw a SocketTimeoutException:
Exception in thread "main" java.net.SocketTimeoutException: Connect timed out
For the server-side, we’ll use the setSoTimeout(int timeout) method to set a timeout value. The timeout value defines how long the ServerSocket.accept() method will block:
ServerSocket serverSocket = new new ServerSocket(port);
serverSocket.setSoTimeout(40000);
Similarly, the timeout unit should be in milliseconds and should be greater than 0. If the timeout elapses before the method returns, it will throw a SocketTimeoutException.
Sometimes, firewalls block certain ports due to security reasons. As a result, a “connection timed out” error can occur when a client is trying to establish a connection to a server. Therefore, we should check the firewall settings to see if it’s blocking a port before binding it to a service.
4. Read Timed Out
4.1. What Is “Read Timed Out”?
The read() method call in the InputStream blocks until it finishes reading data bytes from the socket. The operation waits until it reads at least one data byte from the socket. However, if the method doesn’t return anything after an unspecified time, it throws an InterrupedIOException with a “Read timed out” error message:
java.net.SocketTimeoutException: Read timed out
4.2. Why It Occurs?
From the client side, the “read timed out” error happens if the server is taking longer to respond and send information. This could be due to a slow internet connection, or the host could be offline.
From the server side, it happens when the server takes a long time to read data compared to the preset timeout.
4.3. How to Handle It?
For both the TCP client and server, we can specify the amount of time the socketInputStream.read() method blocks with the setSoTimeout(int timeout) method:
Socket socket = new Socket(host, port);
socket.setSoTimeout(30000);
However, if the timeout elapses before the method returns, the program will throw a SocketTimeoutException.
5. Conclusion
In this article, we discussed the timeout exceptions in Java socket programming, and learned how to handle them.
As always, the code is available over on GitHub.
Всем привет!
Запустил элементарного бота, он отвечает в беседах и тд.. и каждый раз после запуска скрипта(бота) — через некоторое время, python выкидывает ошибку(тоесть после запуска он работает некоторое время, а потом python выдает ошибку): ReadTimeout
Не знаю в чем проблема.
Вот ошибка:
raise ReadTimeout(e, request=request)
request.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.vk.com', port=443): Read timed out. (read timeout=10)
Спасибо)
задан 16 авг 2017 в 14:35
3
Возможно на сервере api vk timeout больше 10-ти секунд, тогда Вам следует указывать его при каждом запросе:
response = requests.post('http://example.com', timeout=20)
Или:
response = requests.get('http://example.com', timeout=20)
ответ дан 22 авг 2017 в 23:08
sakostsakost
1,1385 серебряных знаков15 бронзовых знаков
Проблема в интернет-соединении. Вы можете установить увеличенное время ответа сервера, это уже описали выше. Также советовали обработать это самое исключение. Делается это посредствам блоков try: и except: Более подробно вы можете почитать об это здесь:здесь
ответ дан 8 мая 2020 в 13:53
Судя по всему, ты где-то не закрываешь открытые соединения. Из-за этого соединения в пуле заканчиваются, новые встают в очередь и убиваются по таймауту — вот ты и получаешь такую ошибку.
ответ дан 24 июл 2022 в 0:33
Qwertiy♦Qwertiy
121k24 золотых знака121 серебряный знак291 бронзовый знак
Эта ошибка возникает из-за плохого соединения / бездействия со стороны ВК. К сожалению данную проблему можно исправить только путём игнорирования.
Я предлагаю сделать такой вариант кода (Смею предположить что вы используете LongPoll):
while True:
try:
for event in longpoll.listen():
try:
...
except:
...
except Exception as error:
print(error) # Простая заглушка
# Здесь можно прописать логирование ошибок, но по большей части они связаны с серверами ВК.
У меня написано 2 Бота при помощи такой схемы, всё отлично работает, к сожалению от данной ошибки не избавиться.
ответ дан 31 мар в 17:17
The Java net sockettimeoutexception read timed out error can appear because of a network issue, the server might not respond properly or the firewall blocking the connections.
This article includes all the solutions to these causes and helpful expert recommendations. Keep reading to find out solutions to remove the error.
Contents
- Java Net Sockettimeoutexception Read Timed Out: Causes for the Error
- – Network Issue
- – Server Not Responding
- – Firewall Blocking the Connection
- Java Net Sockettimeoutexception Read Timed Out: Quick Fixes
- – Check Network Connection
- – Increase Timeout Value
- – Check Firewall Configuration
- – Optimize Client Requests
- FAQs
- 1. Where the Java Net Sockettimeoutexception Read Timed Out Can Occur?
- Conclusion
Java Net Sockettimeoutexception Read Timed Out: Causes for the Error
The Java net sockettimeoutexception read timed out error can cause by the network issue, the server might not respond, or the firewall is blocking the connection. There could be multiple reasons for connection failure, like a dense network, any issue with the ISP, a weak router, or a weak firewall.
– Network Issue
The network connection between the client and the server may cause the java net sockettimeoutexception read timed out error. A slow internet connection or a severe issue with the connection itself may be to blame.
To send data between the client and the server within a predetermined time, your internet connection must be quick; otherwise, the connection will be lost. If you go deeper, you’ll discover several causes for the connection failure, including a crowded network, a slow router, a poorly set firewall, or an issue with the ISP.
– Server Not Responding
The java net sockettimeoutexception read timed out error can also occur if the server does not respond to the client’s request in that specific period. The possible reason for your server’s failure to respond timely could be the server is overwhelmed with requests.
If your server receives more requests than its handling capability, processing each request and sending a response will take longer. Or if the client requests a server that involves querying an extensive database or performing a complex calculation, it could take a long time to process.
There could also be a problem with the server itself due to a hardware or software issue, such as a faulty component or a bug in the server software. If this is the case, the server can’t process the request properly, and as a result, you will see the error.
– Firewall Blocking the Connection
A firewall is a security system that controls incoming and outgoing network traffic based on predetermined security rules. If a firewall on either the client or the server side is blocking the connection, it can cause the java net sockettimeoutexception read timed out error to occur.
The firewall might block outgoing connections to the server or incoming connections from the client. This can happen if the firewall has been configured to block connections to specific IP addresses or ports or if the client is behind a corporate firewall with strict rules.
The java net sockettimeoutexception read timed-out error can be solved by checking the network connection, pinging the server, increasing the timeout value, modifying firewall configuration, and optimizing the client’s request. Some solutions are not always helpful as they might affect the overall performance.
– Check Network Connection
If you are facing this issue because of a network issue, the first step to resolving it is to check the network connection and try to resolve any problems. You can perform a basic connectivity test to check the network connection, like pinging the server from the client. This is how you can determine if the client can reach the server or if there are any issues with the connection between the two.
If the connectivity test is successful, the next step should be to identify the problem and troubleshoot it with the network connection. You might check for issues with the router or modem, reset the network hardware, or contact the ISP if there are any issues with the internet connection.
But if the connectivity test goes unsuccessful, there could be any problem with network hardware or software, like a faulty router or misconfigured firewall. If this is the case, you will need to troubleshoot that specific problem and try to fix that problem.
– Increase Timeout Value
If you are facing this issue because of a slow connection or server, try increasing the timeout value in the client application. The timeout value is a setting in the client application to determine how long the client should wait for a response from the server before timing out.
The timeout value is mainly set to a certain number of seconds, and if the client does not receive a response from the server within that period, there is a high chance of facing the error. So when you increase the timeout, you are giving the client more time to wait for a response, or you can say that you are allowing the response that is coming late.
You must change the client application’s code to adjust the timeout value. But before you do, you should know that increasing the timeout number can affect how well the client application performs because the client will take longer to time out if it doesn’t get a response from the server.
Therefore, it’s crucial to balance the necessity for a longer timeout and its effect on the client application’s performance.
– Check Firewall Configuration
Suppose you are facing this error due to a firewall blocking the connection. In that case, the go-to solution is checking the firewall’s configuration and ensuring it is not blocking the connection. You need to access the firewall’s configuration settings and review the rules to do this. These rules determine which incoming and outgoing connections are allowed or blocked by the firewall.
If the firewall is blocking the connection between the client and the server, you will need to change the configuration to allow the connection. This could involve adding an exception rule that allows traffic to and from the client and the server or modifying an existing rule to allow the connection.
Before modifying the firewall’s configuration, you should understand that it can have security implications because it will affect firewall-provided protection. You should also carefully review the firewall rules and ensure that any changes align with the organization’s security policies.
– Optimize Client Requests
If you are facing this error because of a client’s request taking too long to process, one possible solution is to optimize the request to reduce the processing time as a possible solution. You can opt for several ways to optimize the client’s request to reduce the processing time.
One option is to reduce the amount of requested data. If the client is making a request that involves retrieving a large amount of data from the server, It will take a lot of time for the server to process the request and send a response. Doing that means you are reducing the processing time, which eventually can be a solution in your case.
Another option is to optimize the way it is formulated. This could involve more efficient queries or targeted requests that only retrieve the needed data. Optimizing the way the request is formulated can reduce the processing time and fix the error.
FAQs
1. Where the Java Net Sockettimeoutexception Read Timed Out Can Occur?
The java net sockettimeoutexception read timed out can occur while working on any operating system, library, framework, open-source testing tools, or IDE. You might see an altered error message depending on where it appears. Regardless, you can follow the same steps described in this article to eliminate this error.
You can see this error with an altered error message on different operating systems.
- net.sockettimeoutexception read timed out linux
- net.sockettimeoutexception read timed out android.
You can see this error with altered error messages on different Java-based tools and frameworks like this.
- net.sockettimeoutexception read timed out httpclient
- net.sockettimeoutexception read timed out spring boot
You can see this error with altered error messages on applications and platforms like this.
- net.sockettimeoutexception read timed out salesforce
- net.sockettimeoutexception read timed out eclipse
You can see this error with altered error messages on different tools for testing and performance measurement like this.
- net.sockettimeoutexception read timed out JMeter
- net.sockettimeoutexception: read timed out JBoss
Conclusion
Let’s summarize today’s article.
- The java net sockettimeoutexception read timed out can cause network issues, server problems, and firewall configuration.
- A slow internet connection, a crowded network, a slow router, a poorly set firewall, or an issue with the ISP can also cause the problem.
- The quick solutions include checking the network connection and increasing the timeout value.
- You should also try modifying the firewall configuration and optimizing the client’s request.
If you ever face this problem again, you can always come back to seek guidance from this article.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
5
14 комментариев
- популярные
- новые
-
+1Вопросы:
Режим отладки включен? (если включен — выключить)
Используется ли вариант доставки в точки выдачи заказов, настроенных на маркете? (если да, то стоит включить кеширование — memcached или хотя бы файловое)
Настроены ли плагины расчета стоимости доставки, использующие внешние сервисы? (часть плагинов «не сознается» что они используют обращения к внешним ресурсам, а это драгоценное время. Такие плагины лучше не использовать. Решение по облегчению ситуации с ними стоит искать совместно с разработчиками плагинов в сторону оптимизаций расчетов и кеширования)
Маркет лимитирует время на ответ крайне жестко: всего 5.5 секунды
-
+1Добрый день!
Также сталкиваемся с аналогичной проблемой — постоянные ошибки по API http://prntscr.com/czycq3
Магазин у нас в облаке, поэтому мы особо на скорость повлиять не можем. Плагины используются ваши встроенные — курьерская доставка, например.
Какие пути решения посоветуете.
-
+1Если из плагинов доставки у вас установлены только те, которые не обращаются к внешним сервисам для получения стоимости доставки значит, для решения проблемы вам необходимо обратиться в службу поддержки Webasyst.
-
-
+1Аналогичная проблема. Плагин расчета СДЭК скорее всего из за него. Как решить проблему?
-
+1Единственное решение сейчас — не использовать этот плагин (если память не подводит, их сервера не отличаются скоростью ответа на запрос расчета стоимости доставки). Общего решения пока нет (прогнозы по срокам сложно дать), только на уровне отдельных плагинов силами их разработчиков (кеширование/оптимизация).
-
+1я не разработчик таких плагинов, но стало даже интересно …
Тот же СДЭК, например, как кешировать? Мало того, что городов дофига, так он же еще от веса/габаритов, вроде, считает?
-
+1Можно попробовать создать ключ для кеширования на основе параметров, от которых зависит стоимость (вес/габариты можно «квантовать», если поддержка сервиса согласится разгласить величину квантования). Это на повторных запросах даст выигрыш по времени. Можно заранее считать «типовые» заказы (ассортимент известен, в заказ попадает, чаще всего, поштучно, можно попробовать «сгенерировать» кеш для плагинов доставки после сохранения настроек кампании хотя бы для домашнего региона).
-
-
-
-
+1Владислав, я конечно благодарен вам за ответ Вячеславу, как и сам Вячеслав, но на мой вопрос я ответа не получил.
Попробую ещё раз — у нас магазин в облаке, тариф Про. Регулярно вылетают ошибки API Маркета, который подключен через Ваш плагин. Также из Ваших плагинов подключен Courier — т.к. конечный пользователь Маркета должен чётко понимать сколько стоит доставка и Маркет штрафует магазин за несоответствие информации на сайте информации в Маркете.
Таким образом, мы имеем ваше облачное решение + ваши плагины. И регулярные проблемы с API Маркета.
Подскажите, пожалуйста, каким образом решить данные проблемы? Может быть нужно провести какие-то дополнительные настройки силами ваших специалистов за отдельные деньги? Может быть, проблема решится переходом на более дорогой тариф?
Хочется понимать, какие ресурсы и средства необходимы, чтобы решить данную проблему.
-
+1Теперь периодически возникают ошибки HTTP — https://yadi.sk/i/VnvWFXTsxpLNC
Хочется всё же услышать позицию разработчиков, т.к. ошибки Маркет показывает постоянно и ежедневно.
-
+1логи с 500-ой ошибки (скопируйте запрос и ответ сервера и отправьте в запросе в поддержку их) — стоит просмотреть, поскольку ошибка странная.
Про таймаут: из плагинов используется только курьер? включены ли точки самовывоза?
-
+1Ну вот
логи ответа-запроса для случаев 500-ой ошибки не дали, на вопрос об используемых плагинах и точках продаж не ответили (для точек продаж в крайнем обновлении добавилось кеширование, должно уменьшить время ответа).
-
+1Владислав, спасибо за ваши ответы.
про 500 ошибку разобрались — это из-за обновления серверного оборудования.
С техподдержкой ведём беседу, они заботливо предлагают:
1. Не пользоваться плагинами, которые автоматически считают стоимость — из них мы используем ваши же «Курьерская доставка» и «Самовывоз». Считаю, что это неправильно по множеству причин и свою позицию описал техподдержке
2. Попросить Яндекс увеличить timeout для Маркета — осознавая тщетность этой просьбы, я всё же направил в Яндекс письмо и получил единственно логичный ответ: «Указанные таймауты являются глобальными в рамках Маркета и не могут быть изменены в индивидуальном порядке.»
Вот, кстати, новый список ошибок: https://yadi.sk/i/pa9zZjlcxwvVT
-
-
-
+2Добрый день.
Наблюдаем такую же проблему.
Постоянно вылетает Яндекс.
Из плагинов доставки установлены СДЭК и Боксберри.Сегодня прислали вот такое письмо:
Мы заметили, что у вас систематически возникают ошибки в обмене данных через API.Чтобы найти проблему, посмотрите лог запросов к вашему серверу.
Если при повторной проверке мы обнаружим такие же ошибки, нам придётся приостановить работу магазина до тех пор, пока вы не устраните причины их появления.Есть какое-нибудь решение?
I/O error on POST request for "https://SITE.ru/beruru_api/": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out
Эта тема в архиве. Добавление комментариев к ней отключено.