Socket timeout exception ошибка

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 […]

Содержание

  1. How to handle java.net.SocketTimeoutException
  2. How to solve?
  3. From Client side:
  4. Using try/catch/finally
  5. From Server side:
  6. How to Java SocketTimeoutException?
  7. Java.Net.SocketTimeoutException: Connection Timed Out
  8. Sockets in Java
  9. Timeouts in Java
  10. Causes of java.net.SocketTimeoutException: Connection timed out in Java
  11. Solution to java.net.SocketTimeoutException: Connection timed out in Java
  12. java.net.SocketTimeoutException – How to Solve SocketTimeoutException
  13. 1. A simple Cilent-Server application
  14. 1. An example of SocketTimeoutException
  15. 3. How to Solve SocketTimeoutException
  16. Получение java.сеть.SocketTimeoutException: время ожидания соединения в android
  17. 5 ответов
  18. Обработка ошибки тайм-аута в сокетах python
  19. 4 ответов

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:

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

If you are using OkHttp Client then you can add:

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

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?

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.

Источник

Java.Net.SocketTimeoutException: Connection Timed Out

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.

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

The following are some possible reasons for the error.

  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

We can pre-set the timeout option for client and server activities. Adding the try and catch constructs would be an appropriate solution.

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.

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.

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 .

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.

Источник

java.net.SocketTimeoutException – How to Solve SocketTimeoutException

In this example we are going to talk about java.net.SocketTimeoutException . This exception is a subclass of java.io.IOException , so it is a checked exception.

From the javadoc we read that this exception :” Signals that a timeout has occurred on a socket read or accept”. That means that this exception emerges when a blocking operation of the two, an accept or a read, is blocked for a certain amount of time, called the timeout. Let’s say that the socket is configured with a timeout of 5 seconds.

If either the accept() or read() method, blocks for more than 5 seconds, a SocketTimeoutException is thrown, designating that a timeout has occurred. 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.

1. A simple Cilent-Server application

To demonstrate this exception, I’m going to use the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It creates two threads. The first one, SimpleServer , opens a socket on the local machine on port 3333 . Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient , attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it.

As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket. Additionally, you will notice that in SimpleServer I’ve specified the timeout to be of 7 seconds using this method : serverSocket.setSoTimeout(7000); .

So, what we expect to happen here, is the communication to finish normally because the client will connect to the server after 3 seconds. That’s 4 seconds before the timeout barrier is reached. If you run the program, you will see this output :

That means that the client, successfully connected to the server and achieved to transmit its text. Now if you wait a bit more, you will see that a

1. An example of SocketTimeoutException

Now, if you keep the above program running, after the Client said :Hello Mr. Server! message is transmitted successfully, you will notice that a SocketTimeoutException is thrown:

That’s because, after the SimpleServer serves the first client, it loops back to the accept() method to serve the next client in line, but no one is connected. So, when the time out is reached, SocketTimeoutException is thrown.

Of course, you can choose to handle this exception differently. For example , you can choose to loop back to the accept method, even if the exception is thrown, because the socket remains valid.

In the next example, I will launch two client threads with a certain delay between them, so that one of them sends its message before any exception occurs. The other client thread sends its message after an exception is thrown. Let’s see how you can do that, and pay attention to the server thread:

Now if you run the program for a while you will notice that every seven seconds a SocketTimeoutException is thrown :

So as you can see even after the exception is thrown, the socket remains active and receives a message form the second client thread. The above program will keep throwing a SocketTimeoutException every seven seconds.

3. How to Solve SocketTimeoutException

In the above example we’ve shown what causes a SocketTimeoutException in the case of the accept() . The same principles will apply in the case of read() . Now, what can you do to avoid that exception. If the server side application is under your control, you should try yo adjust the timeout barrier so that its more flexible on network delays. You should surely consider doing that especially when your server application will run in a remote machine. Other than that, you can check whatever causes delays in your network, a malfunctioning router etc.

Источник

Получение java.сеть.SocketTimeoutException: время ожидания соединения в android

Я относительно новичок в разработке android. Я разрабатываю приложение для android, где я отправляю запрос на веб-сервер и анализирую объекты json. Часто я получаю java.net.SocketTimeoutException: Connection timed out исключение при общении с сервером. Иногда это будет работать совершенно без каких-либо проблем. Я знаю, что этот вопрос задавали много раз. Но все же я не получил удовлетворительного решения этой проблемы. Я отправляю свой код связи logcat и app-server под.

может ли кто-нибудь помочь мне найти решение для этого? Спасибо заранее.

5 ответов

Я искал по всему интернету и после прочтения многих документов, касающихся исключения тайм-аута соединения, я понял, что предотвращение SocketTimeoutException выходит за рамки нашего предела. Один из способов эффективной обработки-определить тайм-аут соединения,а затем обработать его с помощью блока try catch. надеюсь, это поможет любому в будущем, кто сталкивается с той же проблемой.

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

как указано, ошибка не может быть решена клиентом, так как это проблема, связанная с сетью. Однако вы можете повторить попытку подключения несколько раз. Это может работать как обходной путь, пока реальная проблема не будет исправлена.

возможно, это кому-то помогает.

Если вы тестируете сервер localhost в ваше Android устройство должно быть подключено к той же локальной сети. Затем URL-адрес сервера, используемый вашим приложением, должен включать IP-адрес вашего компьютера, а не маску «localhost».

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

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

Источник

Обработка ошибки тайм-аута в сокетах python

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

способ, которым я добавил модуль сокета, был импортировать все, но как я могу обрабатывать исключения в документах, в которых говорится, что вы можете использовать сокет.timeouterror, но это не работает для меня. Кроме того, как бы я написал блок исключения try, если бы я сделал import socket ? Может кто-то также объяснить разницу в импорте.

4 ответов

добавляет Все имена без подчеркиваниями (или только имена, определенные в модулях ) в foo в текущем модуле.

в приведенном выше коде с from socket import * вы просто хотите поймать timeout как вы потянули timeout в ваше текущее пространство имен.

from socket import * тянет в определениях всего внутри socket но не добавить .

многие люди считают import * проблематично и попытаться избежать этого. Это связано с тем, что общие имена переменных в 2 или более модулях, которые импортируются таким образом, будут мешать друг другу.

например, рассмотрим следующие три файла python:

если вы запустите yourcode.py вы увидите только вывод «это функция foo b».

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

например, ваш код будет выглядеть так с явным импортом:

просто немного больше ввода, но все явное, и это довольно очевидно для читателя, откуда все происходит.

у меня было достаточно успеха просто catchig socket.timeout и socket.error , хотя гнездо.ошибка может быть вызвана по многим причинам. Быть осторожным.

когда вы from socket import * python загружает socket модуль для текущего пространства имен. Таким образом, вы можете использовать члены модуля, как если бы они были определены в текущем модуле python.

Источник

  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

Java.Net.SocketTimeoutException: Connection Timed Out

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

The following are some possible reasons for the error.

  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

We can pre-set the timeout option for client and server activities. Adding the try and catch constructs would be an appropriate solution.

  1. 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);
    
  2. 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.

  3. 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);
    

In this example we are going to talk about java.net.SocketTimeoutException. This exception is a subclass of java.io.IOException, so it is a checked exception.

From the javadoc we read that this exception :” Signals that a timeout has occurred on a socket read or accept”. That means that this exception emerges when a blocking operation of the two, an accept or a read, is blocked for a certain amount of time, called the timeout. Let’s say that the socket is configured with a timeout of 5 seconds.

If either the accept() or read() method, blocks for more than 5 seconds, a SocketTimeoutException is thrown, designating that a timeout has occurred. 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.

1. A simple Cilent-Server application

To demonstrate this exception, I’m going to use the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It creates two threads. The first one, SimpleServer, opens a socket on the local machine on port 3333. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient, attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it.

SocketTimeoutExceptionExample.java:

package com.javacodegeeks.core.net.unknownhostexception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class SocketTimeoutExceptionExample {

	public static void main(String[] args) {

		new Thread(new SimpleServer()).start();
		new Thread(new SimpleClient()).start();

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;
			try {
				
				serverSocket = new ServerSocket(3333);

				serverSocket.setSoTimeout(7000);
				
				while (true) {

					Socket clientSocket = serverSocket.accept();

					BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

					System.out.println("Client said :" + inputReader.readLine());
				}

			} catch (SocketTimeoutException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (serverSocket != null)
						serverSocket.close();

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {

				Thread.sleep(3000);

				socket = new Socket("localhost", 3333);

				PrintWriter outWriter = new PrintWriter(
						socket.getOutputStream(), true);

				outWriter.println("Hello Mr. Server!");

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}
	}
}

As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket. Additionally, you will notice that in SimpleServer I’ve specified the timeout to be of 7 seconds using this method : serverSocket.setSoTimeout(7000);.

So, what we expect to happen here, is the communication to finish normally because the client will connect to the server after 3 seconds. That’s 4 seconds before the timeout barrier is reached. If you run the program, you will see this output:

Client said :Hello Mr. Server!

That means that the client, successfully connected to the server and achieved to transmit its text. Now if you wait a bit more, you will see that a

1. An example of SocketTimeoutException

Now, if you keep the above program running, after the Client said :Hello Mr. Server! message is transmitted successfully, you will notice that a SocketTimeoutExceptionis thrown:

Client said :Hello Mr. Server!
java.net.SocketTimeoutException: Accept timed out
	at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
	at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
	at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
	at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198)
	at java.net.ServerSocket.implAccept(ServerSocket.java:530)
	at java.net.ServerSocket.accept(ServerSocket.java:498)
	at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:35)
	at java.lang.Thread.run(Thread.java:744)

That’s because, after the SimpleServer serves the first client, it loops back to the accept() method to serve the next client in line, but no one is connected. So, when the time out is reached, SocketTimeoutException is thrown.

Of course, you can choose to handle this exception differently. For example , you can choose to loop back to the accept method, even if the exception is thrown, because the socket remains valid.

In the next example, I will launch two client threads with a certain delay between them, so that one of them sends its message before any exception occurs. The other client thread sends its message after an exception is thrown. Let’s see how you can do that, and pay attention to the server thread:

SocketTimeoutExceptionExample.java:

package com.javacodegeeks.core.net.unknownhostexception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class SocketTimeoutExceptionExample {

	public static void main(String[] args) throws InterruptedException {

		new Thread(new SimpleServer()).start();
		new Thread(new SimpleClient()).start();
			
		Thread.sleep(20000);
		
		new Thread(new SimpleClient()).start();

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;

			try {
				serverSocket = new ServerSocket(3333);
				serverSocket.setSoTimeout(7000);

				while (true) {
					try {
						Socket clientSocket = serverSocket.accept();

						BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

						System.out.println("Client said :"+ inputReader.readLine());

					} catch (SocketTimeoutException e) {
						e.printStackTrace();
					}
				}

			} catch (IOException e1) {
				e1.printStackTrace();
			} finally {
				try {
					if (serverSocket != null) {
						serverSocket.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {

				Thread.sleep(3000);

				socket = new Socket("localhost", 3333);

				PrintWriter outWriter = new PrintWriter(
						socket.getOutputStream(), true);

				outWriter.println("Hello Mr. Server!");

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}
	}
}

Now if you run the program for a while you will notice that every seven seconds a SocketTimeoutException is thrown :

Client said :Hello Mr. Server!
java.net.SocketTimeoutException: Accept timed out
	at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
	at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
	at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
	at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198)
	at java.net.ServerSocket.implAccept(ServerSocket.java:530)
	at java.net.ServerSocket.accept(ServerSocket.java:498)
	at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38)
	at java.lang.Thread.run(Thread.java:744)
java.net.SocketTimeoutException: Accept timed out
	at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
	at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
	at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
	at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198)
	at java.net.ServerSocket.implAccept(ServerSocket.java:530)
	at java.net.ServerSocket.accept(ServerSocket.java:498)
	at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38)
	at java.lang.Thread.run(Thread.java:744)
Client said :Hello Mr. Server!
java.net.SocketTimeoutException: Accept timed out
	at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
	at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135)
	at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398)
	at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198)
	at java.net.ServerSocket.implAccept(ServerSocket.java:530)
	at java.net.ServerSocket.accept(ServerSocket.java:498)
	at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38)
	at java.lang.Thread.run(Thread.java:744)
...
...
...

So as you can see even after the exception is thrown, the socket remains active and receives a message form the second client thread. The above program will keep throwing a SocketTimeoutException every seven seconds.

3. How to Solve SocketTimeoutException

In the above example we’ve shown what causes a SocketTimeoutException in the case of the accept(). The same principles will apply in the case of read(). Now, what can you do to avoid that exception. If the server side application is under your control, you should try yo adjust the timeout barrier so that its more flexible on network delays. You should surely consider doing that especially when your server application will run in a remote machine. Other than that, you can check whatever causes delays in your network, a malfunctioning router etc.

Download Source Code

This was an example on java.net.SocketTimeoutException and how to solve SocketTimeoutException. You can download the source code of this example here : SocketTimeoutExceptionExample.zip

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Socket recv socket error
  • Socket recv error 104
  • Socket read error 107
  • Socket protect error openvpn mac
  • Socket processaccept error too many open files

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии