Timeout on a network connection

If you didn’t know that there is a method available, you’d probably think of using a timer thread that closes the connection when it times out. There is an easier way to handle network timeouts. You can have better
control over your socket communications using socket options. And, to make developer’s life easy, there is this useful option called SO_TIMEOUT.

import java.net.*;
import java.io.*;
 
public class Main
{
   public static void main(String args[]) throws Exception {
      if (args.length != 3) {
         System.err.println("Usage: java Main <URL> <PORT> <TIMEOUT>");
         System.exit(1);
      }
  
      Socket s = new Socket(args[0], Integer.parseInt(args[1]));
 
      // set a timeout (in milliseconds)
      s.setSoTimeout(Integer.parseInt(args[2]));
 
      BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
      DataOutputStream dos = new DataOutputStream(s.getOutputStream());
 
      // get the homepage (/) by sending a GET command to the HTTP port
      dos.writeBytes("GET / HTTP/1.0rnrn");
 
      // read response, when timeout occurs, InterruptedIOException is thrown
      try {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch(InterruptedIOException e) {
         System.out.println("Timed out after " + args[2] + " milliseconds.");
      }
      finally {
         br.close();
      }
   }
}

Now try to run it with different values for timeout:

C:> java Main www.yahoo.com 80 10
Timed out after 10 milliseconds.
 
C:> java Main www.esus.com 80 1000
 
[snip: yahoo home]