
// quikconnect demo
// demonstrates how to do connection with timeout

import java.lang.*;     //pld
import java.net.*;      //pld
import java.io.*;

public class quikconnect {
	public quikconnect () {}
    static public BufferedReader bin;
    static public int destport = 5432;
    static public String USAGE = "quikconnect host port timeout_ms";
	static public int timeout = 2000;	// milliseconds
    //============================================================

    static public void main(String args[]) {
		//bin = new BufferedReader(new InputStreamReader(System.in));

		if (args.length < 2) {
			System.err.println(USAGE);
			return;
		}
	    String desthost = args[0]; //"ulam.math.luc.edu";
		destport = (new Integer(args[1])).intValue();
		if (args.length >=3) {
			timeout = (new Integer(args[2])).intValue();
		}
	    InetAddress dest;
        System.err.print("Looking up address of " + desthost + "...");
	    try {
	        dest = InetAddress.getByName(desthost);
	    }
	    catch (UnknownHostException uhe) {
	        System.err.println("unknown host: " + desthost);
	        return;
	    }
	    System.err.println(" got it!");

	    InetSocketAddress sockaddr
	        = new InetSocketAddress(dest, destport);

	    Socket s = new Socket();

	    /*
		// the following creates & connects in one operation,
		// but timeout you can't set the connect timeout:
	    try {
			s = new Socket(dest, destport);
	    } catch(IOException ioe) {
			System.err.println("no socket available");
			return;
	    }
	    /* */

		boolean timeoutflag = false,
				refuseconnectflag = false;

	    try {
	        s.connect(sockaddr, timeout);
		}

	    // The exception here, SocketTimeoutException,
	    // was formerly (jsdk 1.3.x??) known as
	    // "InterruptedIOException"; if you have an old java,
	    // use that instead.
	    catch (SocketTimeoutException ste) {
	        System.err.println("connect timeout");
	        timeoutflag = true;
		}
	    catch (IOException ioe) {
	        System.err.println("connection refused");
	        refuseconnectflag = false;
	    }

	    //============================================================

		if (timeoutflag) {
			System.err.println("socket timeout occurred");
		} else if (refuseconnectflag) {
			System.err.println("socket connection was refused");
		} else {
			System.err.println("closing");
			try {
			   s.close();
			} catch (IOException ioe) {
			   System.err.println("socket close failed");
			   return;
			}	   /* */
		}
	   return;
    }
}

