Ошибка java net socket timeout

With OkHttp library, application is facing following SocketTimeoutException issue. If request size is less, then it is working fine(Less than 1MB). I am getting this exception within 10 seconds, even my socket timeout(readTimeout) value is much higher. It is consistently failing for a request(Size is 1.8MB). When I executed a request with HttpUrlConnection it is working fine. What could be a possible reason of failure?

   03-29 12:16:38.997 32066-4018/com.mobile W/System.err: java.net.SocketTimeoutException: timeout
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.Okio$3.newTimeoutException(Okio.java:207)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.AsyncTimeout.exit(AsyncTimeout.java:261)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.AsyncTimeout$1.write(AsyncTimeout.java:158)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:176)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.write(RealBufferedSink.java:46)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.internal.http.Http1xStream$FixedLengthSink.write(Http1xStream.java:286)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.emitCompleteSegments(RealBufferedSink.java:176)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okio.RealBufferedSink.write(RealBufferedSink.java:96)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.RequestBody$2.writeTo(RequestBody.java:96)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:704)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.internal.http.HttpEngine.readResponse(HttpEngine.java:563)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.RealCall.getResponse(RealCall.java:241)
    03-29 12:16:38.997 32066-4018/com.mobile W/System.err:     at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at okhttp3.RealCall.execute(RealCall.java:57)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at com.mobizio.api.BaseApi.sendOkHttpRequest(BaseApi.java:81)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at com.mobizio.api.BaseApi.doInBackground(BaseApi.java:45)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at com.mobizio.api.BaseApi.doInBackground(BaseApi.java:30)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at java.lang.Thread.run(Thread.java:818)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err: Caused by: java.net.SocketException: socket is closed
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl$SSLOutputStream.write(OpenSSLSocketImpl.java:759)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at okio.Okio$1.write(Okio.java:80)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:     at okio.AsyncTimeout$1.write(AsyncTimeout.java:155)
    03-29 12:16:38.998 32066-4018/com.mobile W/System.err:  ... 20 more

Rainmaker's user avatar

Rainmaker

10.1k9 gold badges52 silver badges88 bronze badges

asked Apr 6, 2016 at 15:29

Vivek's user avatar

2

For OkHttp 3 the default value for OkHttp is 10 seconds. You can increase the timeout to 30 seconds.

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(30, TimeUnit.SECONDS);    // socket timeout

answered Apr 6, 2016 at 16:30

Krish's user avatar

KrishKrish

3,8501 gold badge19 silver badges32 bronze badges

6

I solved that problem increasing writeTimeout().

Try:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES); // read timeout

okHttpClient = builder.build();

answered Oct 11, 2016 at 11:36

Rainmaker's user avatar

RainmakerRainmaker

10.1k9 gold badges52 silver badges88 bronze badges

2

this resolved my problem:

OkHttpClient innerClient = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.MINUTES) // connect timeout
            .writeTimeout(5, TimeUnit.MINUTES) // write timeout
            .readTimeout(5, TimeUnit.MINUTES) // read timeout
            .build();

answered Jul 3, 2019 at 14:11

ronin_99's user avatar

ronin_99ronin_99

3092 silver badges8 bronze badges

4

You need to understand that only adding this won’t solve your problem:

OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

viewModelScope.launch(Dispatchers.IO) {
        try {
            val userListResponseModel = apiEndPointsInterface.usersList()
            returnusersList(userListResponseModel)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel

answered Jun 8, 2020 at 15:56

Kishan Solanki's user avatar

Kishan SolankiKishan Solanki

13.6k4 gold badges83 silver badges81 bronze badges

Use this for Kotlin

 val client1 = OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES) // write timeout
                .readTimeout(2, TimeUnit.MINUTES) // read timeout
                .addInterceptor(
                    BasicAuthInterceptor(
                        AmvaccAppConstants.AUTHENTICATE_USER_NAME, AmvaccAppConstants.AUTHENTICATE_USER_PASSWORD
                    )
                )
                .addInterceptor(interceptor)
                .build()

answered Jul 12, 2019 at 12:31

Pawan Soni's user avatar

Pawan SoniPawan Soni

8508 silver badges19 bronze badges

If you are using Retrofit and Kotlin then use following code:
    var BASE_URL:String="Your URL"
    val clientSetup = OkHttpClient.Builder()
        .connectTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(1, TimeUnit.MINUTES) // write timeout
        .readTimeout(1, TimeUnit.MINUTES) // read timeout
        .build()

    val getClientApi: ApiInterface
        get() {
            var retrofit: Retrofit =  Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(clientSetup)
                .build()
        }

answered Oct 5, 2020 at 12:19

Syed Hasnain's user avatar

1

In my case adding ping interval to OkHttp helps a lot in reducing number of SocketTimeoutExceptions in the app.

OkHttpClient.Builder()
        .pingInterval(3, SECONDS)
        .build()

but i am not sure if these timeouts were related to request size.
I mentioned it also in this issue on github reported to OkHttp library

answered Jan 11, 2022 at 13:02

lukjar's user avatar

lukjarlukjar

7,0652 gold badges31 silver badges40 bronze badges

Run into a Run Catching

runCatching {
       service
}
 .map {
       if (it.isSuccessful && it.body() != null) {
           Success(Unit)
       } else {
           Error(Failure.AuthError.error(it.errorBody()))
       }
}
 .getOrElse {
       Error(Failure.Throwable(it))
}

answered Oct 15, 2021 at 10:21

DavidUps's user avatar

DavidUpsDavidUps

3382 silver badges9 bronze badges

Check if your url is correct. This error can be because of wrong url line

answered Apr 10, 2021 at 9:58

kham Ham's user avatar

1

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.java net sockettimeoutexception read timed out

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.Java Net Sockettimeoutexception Read Timed Out Causes

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.Java Net Sockettimeoutexception Read Timed Out Fixes

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

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  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

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

В этом примере мы поговорим о java.net.SocketException. Это подкласс IOException, поэтому это проверенное исключение, которое сигнализирует о проблеме при попытке открыть или получить доступ к сокету.

Настоятельно рекомендуется использовать самый «определенный» класс исключений сокетов, который более точно определяет проблему. Стоит также отметить, что SocketException, выдаётся на экран с сообщением об ошибке, которое очень информативно описывает ситуацию, вызвавшую исключение.

Простое клиент-серверное приложение

Чтобы продемонстрировать это исключение, я собираюсь позаимствовать некоторый код из клиент-серверного приложения, которое есть в java.net.ConnectException. Он состоит из 2 потоков.

  • Поток 1 – SimpleServer, открывает сокет на локальном компьютере через порт 3333. Потом он ожидает установления соединения. Если происходит соединение, он создает входной поток и считывает 1 текстовую строчку, от клиента, который был подключен.
  • Поток номер 2 – SimpleClient, подключается к сокету сервера, открытого SimpleServer. Он отправляет одну текстовую строчку.

Получается, что 2 потока будут в разных классах, запущенных двумя разными основными методами, чтобы вызвать исключение:

package com.javacodegeeks.core.socketecxeption;

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


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

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

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;

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

				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();
				}
			}
		}
	}
}

SimpleClientApp.java:

package com.javacodegeeks.core.socketecxeption;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;


public class SimpleClientApp {

	public static void main(String[] args) {
		
		new Thread(new SimpleClient()).start();

	}
	
	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {

				socket = new Socket("localhost", 3333);
				
				PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
				
				System.out.println("Wait");

				Thread.sleep(15000);

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

			}catch (SocketException e) {
				e.printStackTrace();
			}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();
				}
			}
		}
	}
}

Как вы можете видеть, я поместил в SimpleClient 15-секундную задержку, прежде чем попытаться отправить свое сообщение. К тому моменту, когда клиент вызывает sleep(), он уже создал соединение с сервером. Я собираюсь запустить оба потока, и после того, как клиент установит соединение, я внезапно остановлю клиентское приложение.
Вот что происходит на стороне сервера:

java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:196)
	at java.net.SocketInputStream.read(SocketInputStream.java:122)
	at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
	at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
	at java.io.InputStreamReader.read(InputStreamReader.java:184)
	at java.io.BufferedReader.fill(BufferedReader.java:154)
	at java.io.BufferedReader.readLine(BufferedReader.java:317)
	at java.io.BufferedReader.readLine(BufferedReader.java:382)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.
SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36)
	at java.lang.Thread.run(Thread.java:744)

Мы получаем исключение SocketException с сообщением «Сброс подключения». Это происходит, когда один из участников принудительно закрывает соединение без использования close().

Конечно, вы можете сделать оперативное закрытие соединения, не закрывая приложение вручную. В коде клиента, после ожидания в течение 15 секунд (или меньше), вы можете выдать новое исключение (используя throws new Exception ()), но вы должны удалить finally, иначе соединение будет нормально закрываться, и SocketException не будет сброшен.

SocketException – это общее исключение, обозначающее проблему при попытке доступа или открытия Socket. Решение этой проблемы должно быть сделано с особой тщательностью. Вы должны всегда регистрировать сообщение об ошибке, которое сопровождает исключение.

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

Также может быть сообщение «Слишком много открытых файлов», особенно если вы работаете в Linux. Это сообщение обозначает, что многие файловые дескрипторы открыты для системы. Вы можете избежать этой ошибки, если перейдете в /etc/sysctl.conf и увеличите число в поле fs.file-max. Или попытаться выделить больше стековой памяти.

Конечно, можно встретить много других сообщений. Например, «Ошибка привязки», где ваше соединение не может быть установлено, поскольку порт не может быть привязан к сокету. В этом случае проверьте, используется ли порт и т. д.

Если у вас проблема с minecraft, то чтобы решить проблему попробуйте сделать следующее:

  1. Обновите джаву, скачайте по ссылке https://www.java.com/ru/download/ новую версию и установите;
  2. Возможно блокирует антивирус или брандмауэр. Отключите антивирус и добавьте minecraft в список исключения в брандмауэре (или его можно выключить на время).
  3. При запуске игры, в правом нижнем углу отображается версия игры, если у вас не последняя версия, то обновите.
  4. Если у вас много расширений и модов, то это может приводить к багам, удалите последние установленные моды – это может решить проблему.
  5. Если вы используете платный сервер и у вас закончилась подписка, то опять же у вас будет такая ошибка.

Играя в 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 области памяти. Увеличьте лимит памяти в настройках лаунчера.

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.

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

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

  • Ошибка java net connectexception connection refused no further information
  • Ошибка java net connect
  • Ошибка java lang unsatisfiedlinkerror
  • Ошибка java lang securityexception permission denial
  • Ошибка java lang runtimeexception java lang nullpointerexception