Home » Core Java » net » Socket » Create client Socket with timeout

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments