// The Date Client - The date client connects to the server, sends the "GetDate" command and
// waits for a response.
// by Derek Molloy

import java.net.*;
import java.io.*;
import java.util.*;

public class DateClient 
{

    private Socket socket = null;
    private ObjectOutputStream os = null;
    private ObjectInputStream is = null;

    // the constructor expects the IP address of the server - the port is fixed at 5050
    public DateClient(String serverIP) 
    {
	if (!connectToServer(serverIP)) 
        {
	   System.out.println("Cannot open socket connection...");            
	}
    }

    private boolean connectToServer(String serverIP) 
    {
	try  // open a new socket to port: 5050 and create streams
        {
	   this.socket = new Socket(serverIP,5050);
	   this.os = new ObjectOutputStream(this.socket.getOutputStream());
	   this.is = new ObjectInputStream(this.socket.getInputStream());
	   System.out.print("Connected to Server\n");
	} 
        catch (Exception ex) 
        {
	  System.out.print("Failed to Connect to Server\n" + ex.toString());	
	  System.out.println(ex.toString());
	  return false;
	}
	return true;
    }

    private void getDate() 
    {
       String theDate;
       System.out.println("GetDate");
       this.send("GetDate");
       theDate = (String)receive();
       if (theDate != null)
       {
	  System.out.println("The Server's date is " + theDate);
       }
    }
	
    // method to send a generic object.
    private void send(Object o) 
    {
	try 
        {
	   System.out.println("Sending " + o);
	   os.writeObject(o);
	   os.flush();
	} 
        catch (Exception ex) 
        {
	   System.out.println(ex.toString());
	}
    }

    // method to receive a generic object.
    private Object receive() 
    {
	Object o = null;
	try 
        {
	   o = is.readObject();
	} 
        catch (Exception ex) 
        {
	   System.out.println(ex.toString());
	}
	return o;
    }

    public static void main(String args[]) 
    {
	if(args.length>0)
	{
	   DateClient theApp = new DateClient(args[0]);
	   try
           {
              theApp.getDate();
 	   } 
           catch (Exception ex)
           {
	      System.out.println(ex.toString());
	   }
	}
	else
	{
	   System.out.println("Error: you must provide the IP of the server");
	   System.exit(1);
	}
	System.exit(0);
    }
}
