Java socket timeout exception ошибка

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

I am trying to call my remote tomcat server from java client but i intermittently get SocketTimeoutException: connection time out. (http://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html)

here is the stack trace

Caused by: java.net.SocketTimeoutException: connect timed out
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:365)
        at java.net.Socket.connect(Socket.java:527)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:570)
        at org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory.createSocket(EasySSLProtocolSocketFactory.java:189)
        at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)
        at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
        at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)

It is not consistent, it goes away after my code makes multiple attempt to connect.

i understand what socketTimeout means, I am not getting read time out but connect time out, which means client fails to setup tcp connection with the server.Meaning server just disregards the clients attempt to connect it, as either its not available or too busy doing something else on that port. I know my server is reachable and up and running.

apparently my attempt to connect to the server is being refused, i want to figure out why? how do i get started? what should i look for? my server runs on redhat linux box running on an EC2 instance, is there a way i can look at why my connection is being refused?

Nov 20, 2017 6:00:35 PM |
Java Exception Handling — SocketTimeoutException

A deep dive into the Java SocketTimeoutException, with functional code samples showing how to create a client/server socket connection.

Making our way through our in-depth Java Exception Handling series, today we’ll be going over the SocketTimeoutException. As you may suspect based on the name, the SocketTimeoutException is thrown when a timeout occurs during a read or acceptance message within a socket connection.

Throughout this article we’ll explore the SocketTimeoutException in more detail, starting with where it resides in the overall Java Exception Hierarchy. We’ll then look at some functional sample code that will illustrate how a common socket connection might be established, and how failure to plan ahead for potential connection timeouts can lead to unexpected SocketTimeoutExceptions. Let’s get this party started!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

  • java.lang.Object
    • java.lang.Throwable
      • java.lang.Error
        • java.io.IOException
          • java.io.InterruptedIOException
            • SocketTimeoutException

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

// Server.java
package io.airbrake.sockettimeoutexception;

import io.airbrake.utility.Logging;

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;

public class Server {

private final static int DefaultPort = 24601;

public static void main(String[] args) {
CreateServer();
}

private static void CreateServer() {
CreateServer(DefaultPort);
}

/**
* Create a socket server at passed port.
*
* @param port Port onto which server is socketed.
*/
private static void CreateServer(int port) {
try {
Logging.lineSeparator(String.format("CREATING SERVER: localhost:%d", port));
// Established server socket at port.
ServerSocket serverSocket = new ServerSocket(port);

while (true) {
// Listen for connection.
Socket socket = serverSocket.accept();
// Once client has connected, use socket stream to send a prompt message to client.
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
// Prompt for client.
printWriter.println("Enter a message for the server.");

// Get input stream produced by client (to read sent message).
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String output = bufferedReader.readLine();

// Output sent message from client.
printWriter.println(output);

// Close writer and socket.
printWriter.close();
socket.close();

// Output message from client.
Logging.log(String.format("[FROM Client] %s", output));

// Loop back, awaiting a new client connection.
}
} catch (SocketTimeoutException exception) {
// Output expected SocketTimeoutExceptions.
Logging.log(exception);
} catch (IOException exception) {
// Output unexpected IOExceptions.
Logging.log(exception, false);
}
}
}

// Client.java
package io.airbrake.sockettimeoutexception;

import io.airbrake.utility.Logging;

import java.io.*;
import java.net.*;

public class Client {
private final static String DefaultHost = "localhost";
private final static int DefaultPort = 24601;
private final static int DefaultTimeout = 2000;
private final static boolean DefaultShouldSleep = false;

private String Message;

public Client() {
// Default connection.
Connect();

// Attempt to connect using 1 millisecond timeout.
Connect(DefaultHost, DefaultPort, 1, DefaultShouldSleep);

// Attempt to connect using 1 millisecond timeout, with artificial sleep to simulate connection delay.
Connect(DefaultHost, DefaultPort, 1, true);
}

private void Connect() {
Connect(DefaultHost, DefaultPort, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(String host) {
Connect(host, DefaultPort, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(int port) {
Connect(DefaultHost, port, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(boolean shouldSleep) {
Connect(DefaultHost, DefaultPort, DefaultTimeout, shouldSleep);
}

/**
* Connect to passed host and port as client.
*
* @param host Host to connect to.
* @param port Port to connect to.
* @param timeout Timeout (in milliseconds) to allow for socket connection.
* @param shouldSleep Indicates if thread should be artificially slept.
*/
private void Connect(String host, int port, int timeout, boolean shouldSleep) {
try {
Logging.lineSeparator(
String.format(
"CONNECTING TO %s:%d WITH %d MS TIMEOUT%s",
host,
port,
timeout,
shouldSleep ? " AND 500 MS SLEEP" : ""
),
80
);

while (true) {
Socket socket = new Socket();
// Connect to socket by host, port, and with specified timeout.
socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), timeout);

// Read input stream from server and output said message.
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Check if artificial sleep should occur, to simulate connection delay.
if (shouldSleep) {
// Sleep for half a second.
Thread.sleep(500);
}

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

Logging.log("[FROM Server] " + reader.readLine());

// Await user input via System.in (standard input stream).
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
// Save input message.
Message = userInputBR.readLine();

// Send message to server via output stream.
writer.println(Message);

// If message is 'quit' or 'exit', intentionally disconnect.
if ("quit".equalsIgnoreCase(Message) || "exit".equalsIgnoreCase(Message)) {
Logging.lineSeparator("DISCONNECTING");
socket.close();
break;
}

Logging.log("[TO Server] " + reader.readLine());
}
} catch (SocketTimeoutException exception) {
// Output expected SocketTimeoutExceptions.
Logging.log(exception);
} catch (InterruptedException | IOException exception) {
// Output unexpected InterruptedExceptions and IOExceptions.
Logging.log(exception, false);
}
}
}

// Main.java
package io.airbrake;

import io.airbrake.sockettimeoutexception.Client;

public class Main {

public static void main(String[] args) {
Client client = new Client();
}
}

This code sample also uses the Logging utility class, the source of which can be found here on GitHub.

When Should You Use It?

A SocketTimeoutException can really occur under only a handful of circumstances (at least, while using the standard Java libraries). All of these scenarios occur when dealing directly with the Socket class, which allows for client sockets to be established to remote endpoints. In other words, Sockets are used to establish connections between two systems, including the common client and server configuration that’ll be using today in our example code.

To begin we’ll need the Server class:

// Server.java
package io.airbrake.sockettimeoutexception;

import io.airbrake.utility.Logging;

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;

public class Server {

private final static int DefaultPort = 24601;

public static void main(String[] args) {
CreateServer();
}

private static void CreateServer() {
CreateServer(DefaultPort);
}

/**
* Create a socket server at passed port.
*
* @param port Port onto which server is socketed.
*/
private static void CreateServer(int port) {
try {
Logging.lineSeparator(String.format("CREATING SERVER: localhost:%d", port));
// Established server socket at port.
ServerSocket serverSocket = new ServerSocket(port);

while (true) {
// Listen for connection.
Socket socket = serverSocket.accept();
// Once client has connected, use socket stream to send a prompt message to client.
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
// Prompt for client.
printWriter.println("Enter a message for the server.");

// Get input stream produced by client (to read sent message).
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String output = bufferedReader.readLine();

// Output sent message from client.
printWriter.println(output);

// Close writer and socket.
printWriter.close();
socket.close();

// Output message from client.
Logging.log(String.format("[FROM Client] %s", output));

// Loop back, awaiting a new client connection.
}
} catch (SocketTimeoutException exception) {
// Output expected SocketTimeoutExceptions.
Logging.log(exception);
} catch (IOException exception) {
// Output unexpected IOExceptions.
Logging.log(exception, false);
}
}
}

The Server class file also includes a main(...) method so we can easily execute the server creation process in a separate thread from our client code, which we’ll look at in a moment. Overall, the server is established by creating a new ServerSocket instance, associated with the specified port. We then enter a constant loop listening for incoming socket connections and printing out a stream with the data message sent by the client, if applicable. This process repeats until the connection is lost or an error occurs.

Meanwhile, our Client class is slightly more complex, but still fairly simple:

// Client.java
package io.airbrake.sockettimeoutexception;

import io.airbrake.utility.Logging;

import java.io.*;
import java.net.*;

public class Client {
private final static String DefaultHost = "localhost";
private final static int DefaultPort = 24601;
private final static int DefaultTimeout = 2000;
private final static boolean DefaultShouldSleep = false;

private String Message;

public Client() {
// Default connection.
Connect();

// Attempt to connect using 1 millisecond timeout.
Connect(DefaultHost, DefaultPort, 1, DefaultShouldSleep);

// Attempt to connect using 1 millisecond timeout, with artificial sleep to simulate connection delay.
Connect(DefaultHost, DefaultPort, 1, true);
}

private void Connect() {
Connect(DefaultHost, DefaultPort, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(String host) {
Connect(host, DefaultPort, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(int port) {
Connect(DefaultHost, port, DefaultTimeout, DefaultShouldSleep);
}

private void Connect(boolean shouldSleep) {
Connect(DefaultHost, DefaultPort, DefaultTimeout, shouldSleep);
}

/**
* Connect to passed host and port as client.
*
* @param host Host to connect to.
* @param port Port to connect to.
* @param timeout Timeout (in milliseconds) to allow for socket connection.
* @param shouldSleep Indicates if thread should be artificially slept.
*/
private void Connect(String host, int port, int timeout, boolean shouldSleep) {
try {
Logging.lineSeparator(
String.format(
"CONNECTING TO %s:%d WITH %d MS TIMEOUT%s",
host,
port,
timeout,
shouldSleep ? " AND 500 MS SLEEP" : ""
),
80
);

while (true) {
Socket socket = new Socket();
// Connect to socket by host, port, and with specified timeout.
socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), timeout);

// Read input stream from server and output said message.
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Check if artificial sleep should occur, to simulate connection delay.
if (shouldSleep) {
// Sleep for half a second.
Thread.sleep(500);
}

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

Logging.log("[FROM Server] " + reader.readLine());

// Await user input via System.in (standard input stream).
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
// Save input message.
Message = userInputBR.readLine();

// Send message to server via output stream.
writer.println(Message);

// If message is 'quit' or 'exit', intentionally disconnect.
if ("quit".equalsIgnoreCase(Message) || "exit".equalsIgnoreCase(Message)) {
Logging.lineSeparator("DISCONNECTING");
socket.close();
break;
}

Logging.log("[TO Server] " + reader.readLine());
}
} catch (SocketTimeoutException exception) {
// Output expected SocketTimeoutExceptions.
Logging.log(exception);
} catch (InterruptedException | IOException exception) {
// Output unexpected InterruptedExceptions and IOExceptions.
Logging.log(exception, false);
}
}
}

The Connect(String host, int port, int timeout, boolean shouldSleep) method overload is where most of the logic occurs, but we’ve also added a number of other Connect(...) method overloads for simplicity and usability, relying on a handful of default property values for things like the host, port, and timeout period. Just as with our server code, the Client connection process creates an infinite loop in which it establishes a new Socket, then attempts a direct connection to the specified host and port. Critically, we’re also passing the second parameter to the Socket.connect(...) method, which indicates the timeout period (in milliseconds) that the connection is allowed before timing out.

Once a connection is established the client creates a reader and writer, which we use to send and receive data messages between the server. The client can write messages in the console, which are sent to the server and the server will respond to the client, in kind. Sending quit or exit will close the connection and exit the loop.

To test things out we start with a baseline connection test. First we must initialize our Server:

public static void main(String[] args) {
CreateServer();
}

As expected, this outputs a confirmation indicating the server is up and running:

--- CREATING SERVER: localhost:24601 ---

Now, we’ll begin with a basic client connection using our default parameters:

public Client() {
// Default connection.
Connect();

// ...
}

The client output shows that a connection was established and the server sends a message prompting us for some input:

-------------- CONNECTING TO localhost:24601 WITH 2000 MS TIMEOUT --------------
[FROM Server] Enter a message for the server.

Let’s just say «hello» to the server, which outputs the following for the client:

Hello
[TO Server] Hello

Meanwhile, the server receives the message and outputs this;

[FROM Client] Hello world

Cool. Everything seems to be working as expected. If we type exit or quit we’ll close the client connection and can move onto the next test:

quit
------------ DISCONNECTING -------------

Our next Connect(...) method call includes a 1 millisecond timeout:

// Attempt to connect using 1 millisecond timeout.
Connect(DefaultHost, DefaultPort, 1, DefaultShouldSleep);

Normally, 1 millisecond is an exceptionally inadequate timeout period. However, since both the client and server are running locally in our development setup, running this code will usually not result in any problems. As we see here, we were able to connect without experiencing a timeout, and successfully sent another message to the server:

--------------- CONNECTING TO localhost:24601 WITH 1 MS TIMEOUT ----------------
[FROM Server] Enter a message for the server.
Hi, again.
[TO Server] Hi, again.

To simulate an actual delayed network connection we’ll lastly try adding an explicit pause during our connection process by calling Thread.sleep(...) within the Connect(...) method:

// Attempt to connect using 1 millisecond timeout, with artificial sleep to simulate connection delay.
Connect(DefaultHost, DefaultPort, 1, true);

Executing this code will typically throw a SocketTimeoutException our way, indicating that the connection could not be established within the extremely short one millisecond timeout period:

------- CONNECTING TO localhost:24601 WITH 1 MS TIMEOUT AND 500 MS SLEEP -------
[EXPECTED] java.net.SocketTimeoutException

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring, Maven, log4j, Struts, Kotlin, Grails, Groovy, and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

  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.

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 scanner обработка ошибок
  • Java net sockettimeoutexception read timed out ошибка
  • Java memory out of heap space ошибка
  • Java lang string ошибка
  • Java io ioexception ошибка при проверке ключа

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

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