Socket

Create client Socket with timeout

In this example we shall show you how to create a client Socket with timeout. A client socket is an endpoint for communication between two machines. To create a client socket with timeout one should perform the following steps:

  • Get the InetAddress of a specified host, using the host’s name, with getByName(String host) API method of InetAddress.
  • Create a new InetSocketAddress that implements an IP Socket Address, with the InetAddress and the port.
  • Create a new Socket and connect it to the server with a specified timeout value, using connect(SocketAddress endpoint, int timeout) API method of Socket. If timeout occurs, a SocketTimeoutException is thrown,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class CreateClientSocketWithTimeout {
	
	public static void main(String[] args) {
		
		try {
			
			InetAddress addr = InetAddress.getByName("javacodegeeks.com");
		    int port = 80;

		    SocketAddress sockaddr = new InetSocketAddress(addr, port);

		    // Creates an unconnected socket
		    Socket socket = new Socket();

		    int timeout = 5000;   // 5000 millis = 5 seconds
		    
		    // Connects this socket to the server with a specified timeout value
		    // If timeout occurs, SocketTimeoutException is thrown
		    socket.connect(sockaddr, timeout);
			
			System.out.println("Socket connected..." + socket);
		    
		}
		catch (UnknownHostException e) {
			System.out.println("Host not found: " + e.getMessage());
		}
		catch (IOException ioe) {
			System.out.println("I/O Error " + ioe.getMessage());
		}
		
	}

}

Output:

Socket connected... Socket[addr=javacodegeeks.com/216.239.34.21,port=80,localport=58897]

 
This was an example of how to create a client socket with timeout in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Miguel
Miguel
2 years ago

Worked in android, thanks!

20210331_181357.jpg
Back to top button