import java.net.*;
import java.util.*;
import java.io.*;

/**
 *
 * CSTestClient
 * <BR><BR>
 * Test Client for the CommServer.  
 *
 * @author  Derek Clayton   derek_clayton@iceinc.com
 * @version 1.0.0
 */

public class CSTestClient {
    private Socket socket;          // socket for connection
    private String ip;              // ip of server to test
    private int port;            // port of server to test

    /**
     * Constructor for the CSTestClient.  Initializes the CSTestClient 
     * properties.
     * @param   ip      ip of server to test
     * @param   port    port of server to test
    */
    public CSTestClient(String ip, String port) {
        this.ip = ip;
        this.port = (Integer.decode(port)).intValue();
        
        testServer();
    }

    private void testServer() {
        writeActivity("Attempting to connect to server at " +
        ip + ":" + port);
        
        // --- attempt to get a connection to the server
        try {
            socket = new Socket(ip, port);
        } catch (UnknownHostException uhe) {
            writeActivity("Unknown Host Exception: " + uhe.getMessage());
        } catch (IOException ioe) {
            writeActivity("IO Exception: " + ioe.getMessage());
        }
        
        // --- write what happened on the attempt
        if(socket != null) {
            writeActivity("Connection SUCCESSFUL");
            try {
                socket.close();
            } catch (IOException ioe) {
                writeActivity("IO Exception: " + ioe.getMessage());
            }
        } else {
            writeActivity("Connection FAILED");
        }
    }
    
       /**
     * Writes a message to System.out.println in the format
     * [mm/dd/yy hh:mm:ss] message.
     * @param   activity    The message.
    */
    public void writeActivity(String activity) {
        // --- get the current date and time
        Calendar cal = Calendar.getInstance();
        activity = "[" + cal.get(Calendar.MONTH) 
                 + "/" + cal.get(Calendar.DAY_OF_MONTH) 
                 + "/" + cal.get(Calendar.YEAR) 
                 + " " 
                 + cal.get(Calendar.HOUR_OF_DAY) 
                 + ":" + cal.get(Calendar.MINUTE) 
                 + ":" + cal.get(Calendar.SECOND) 
                 + "] " + activity + "\n";

        // --- display the activity
        System.out.print(activity);
    }
    
    public static void main(String args[]) {
        // --- if correct number of arguments
        if(args.length == 2) {
            CSTestClient myCSTC = new CSTestClient(args[0], args[1]);
        } else {
        // otherwise give correct usage
            System.out.println("Usage: java CSTestClient [ip] [port]");
        }
    }
}