Skip to content
Snippets Groups Projects
LennonHW2Client.java 5.28 KiB
package MV3500Cohort2024JulySeptember.homework2.Lennon;

//import TcpExamples.TcpExample3Client;
//import TcpExamples.TcpExample4DispatchServer;
//import TcpExamples.TcpExample4HandlerThread;
import java.io.*;
import java.net.*;
import java.util.Scanner;
//import java.time.LocalTime; // conversion?

/**
 * This client program establishes a socket connection to the {@link TcpExample4DispatchServer},
 * then checks how long it takes to read the single line it expects as a server response.
 * No fancy footwork here, it is pretty simple and similar to {@link TcpExample3Client}.
 * 
 * @see TcpExample4DispatchServer
 * @see TcpExample4HandlerThread
 *
 * @see <a href="../../../src/TcpExamples/TcpExample4TerminalLog.txt" target="blank">TcpExample4TerminalLog.txt</a>
 * @see <a href="../../../src/TcpExamples/TcpExample4SequenceDiagram.png" target="blank">TcpExample4SequenceDiagram.png</a>
 * @see <a href="../../../src/TcpExamples/TcpExample4SequenceSketch.png" target="blank">TcpExample4SequenceSketch.png</a>
 * 
 * @author Don McGregor
 * @author Don Brutzman
 * @author MV3500 class
 */
public class LennonHW2Client
{
    /** Default constructor */
    public LennonHW2Client()
    {

        // default constructor
    }
    static String DESTINATION_HOST = "localhost";
    static int    MAX_LOOP_COUNT   = 4;

    /**
     * Program invocation, execution starts here
     * @param args command-line arguments
     */
    public static void main(String[] args) {
        try {
            boolean play;
            Scanner scanner = new Scanner(System.in);
            System.out.println(LennonHW2Client.class.getName() + " start, loop " + MAX_LOOP_COUNT + " times");
            
            //for (int loopCount = 1; loopCount <= MAX_LOOP_COUNT; loopCount++) // loop then exit
            do{
                System.out.println("=======================================================");
                System.out.println(LennonHW2Client.class.getName() + " creating new socket ...\n");

                // We request an IP to connect to ("localhost") and
                // port number at that IP (2317). This establishes
                // a connection to that IP in the form of the Socket
                // object; the server uses a ServerSocket to wait for
                // connections.
                

                // open a socket for each loop
		Socket socket = new Socket(DESTINATION_HOST, 2317);
                long startTime = System.currentTimeMillis();

                // Setup.  Read the single line written by the server.
                // We'd do things a bit differently if many lines to be read
                // from the server, instead of one only.
                InputStream is = socket.getInputStream();
                Reader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String serverMessage = br.readLine(); // blocks
                System.out.println("Message from server:" + serverMessage);
                String guess = null;
                boolean validGuess = false;
                while(!validGuess){
                    guess = scanner.nextLine();
                    try{
                        int numGuess = Integer.parseInt(guess);
                        if (numGuess < 1 || numGuess > 10){
                            System.out.println("I said between 1 and 10. Guess Again");
                            continue;
                        }
                        validGuess = true;
                    }
                    catch(NumberFormatException e){
                        System.out.println("That's not a number. Guess Again");
                    }
                }
                OutputStream os = socket.getOutputStream();
                PrintStream ps = new PrintStream(os);
                
                ps.println(guess); 
                ps.flush();
                
                is = socket.getInputStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);

                serverMessage = br.readLine(); // blocks
                long endTime = System.currentTimeMillis();
                long timeLength = endTime - startTime;

                System.out.println("\nMessage from server:" + serverMessage);
                System.out.println("Time to play = " + timeLength);                
                
                System.out.println("\nWant to go again? Y/N");

                String response = scanner.nextLine();
                play = "Y".equals(response.toUpperCase());
            }while(play);
            System.out.println("\nGOODBYE");
            System.out.println("=======================================================");
            System.out.println(LennonHW2Client.class.getName() + " complete");
            // main method now exits
        } catch (IOException e) {
            System.out.println("Problem with " + LennonHW2Client.class.getName() + " networking:networking:"); // describe what is happening
            System.out.println("Error: " + e);
            // Provide more helpful information to user if exception occurs due to running twice at one time
            if (e instanceof java.net.BindException) {
                System.out.println("*** Be sure to stop any other running instances of programs using this port!");
            }
        }
    }
}