Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Introduction

In this tutorial, we'll focus on the timeout exceptions of Java socket programming. Our goal is to understand why these exceptions occur and how to handle them.

2. Java Sockets and Timeouts

A socket is one end-point of a logical link between two computer applications. In other words, it's a logical interface applications use to send and receive data over the network.

In general, a socket is a combination of an IP address and a port number. Each socket is assigned with a specific port number that is used to identify the service.

Connection-based services use TCP-based stream sockets. For this reason, Java provides the class for client-side programming. On the other hand, server-side TCP/IP programming makes use of the class.

Another type of socket is the UDP-based datagram socket which is used for connectionless services. Java provides for UDP operations. However, in this tutorial, we'll focus on TCP/IP sockets.

3. Connection Timed Out

3.1. What Is “Connection Timed Out”?

For establishing a connection to the server from the client-side, the socket constructor is invoked, which instantiates a socket object. The constructor takes the remote host address and the port number as input arguments. After that, it attempts to establish a connection to the remote host based on the given parameters.

The operation blocks all other processes until a successful connection is made. However, if the connection isn't successful after a certain time, the program throws a ConnectionException with a “Connection timed out” message: Connection timed out: connect

From the server-side, the ServerSocket class continuously listens to incoming connection requests. When ServerSocket receives a connection request, it invokes the accept() method to instantiate a new socket object. Similarly, this method also blocks until it establishes a successful connection with the remote client.

In case the TCP handshakes are not complete, the connection remains unsuccessful. Consequently, the program throws an IOException indicating an error occurred while establishing a new connection.

3.2. Why It Occurs?

There can be several reasons for a connection timeout error:

  • No service is listening to the given port on the remote host
  • The remote host is not accepting any connection
  • The remote host is not available
  • Slow internet connection
  • No forwarding path to the remote host

3.3. How to Handle It?

Blocking times are not bounded, and a programmer can pre-set the timeout option for both client and server operations. For the client-side, we'll first create an empty socket. After that, we'll use the connect(SocketAddress endpoint, int timeout) method and set the timeout parameter:

Socket socket = new Socket(); 
SocketAddress socketAddress = new InetSocketAddress(host, port); 
socket.connect(socketAddress, 30000);

The timeout unit is in milliseconds and should be greater than 0. However, if the timeout expires before the method call returns, it will throw a SocketTimeoutException:

Exception in thread "main" Connect timed out

For the server-side, we'll use the setSoTimeout(int timeout) method to set a timeout value. The timeout value defines how long the ServerSocket.accept() method will block:

ServerSocket serverSocket = new new ServerSocket(port);

Similarly, the timeout unit should be in milliseconds and should be greater than 0. If the timeout elapses before the method returns, it will throw a SocketTimeoutException.

Sometimes, firewalls block certain ports due to security reasons. As a result, a “connection timed out” error can occur when a client is trying to establish a connection to a server. Therefore, we should check the firewall settings to see if it's blocking a port before binding it to a service.

4. Read Timed Out

4.1. What Is “Read Timed Out”?

The read() method call in the InputStream blocks until it finishes reading data bytes from the socket. The operation waits until it reads at least one data byte from the socket. However, if the method doesn't return anything after an unspecified time, it throws an InterrupedIOException with a “Read timed out” error message: Read timed out

4.2. Why It Occurs?

From the client side, the “read timed out” error happens if the server is taking longer to respond and send information. This could be due to a slow internet connection, or the host could be offline.

From the server side, it happens when the server takes a long time to read data compared to the preset timeout.

4.3. How to Handle It?

For both TCP client and server, we can specify the amount of time the method blocks with the setSoTimeout(int timeout) method:

Socket socket = new Socket(host, port);

However, if the timeout elapses before the method returns, the program will throw a SocketTimeoutException.

5. Conclusion

In this article, we went through the timeout exceptions in Java socket programming and learned how to handle them.

As always, the code is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Inline Feedbacks
View all comments