Skip to content
Snippets Groups Projects
Client.java 2.51 KiB
package MV3500Cohort2024JulySeptember.homework2.Smith;

/**
 * This the the rock paper sciccors client.
 * @author tjsus
 */
import java.io.*;
import java.net.*;
import java.util.Scanner;

/**
 * Client Class
 * @author tjsus
 */

public class Client {
    /**
     * Client constructor
     */
    public Client() {
        // default constructor
    }

    /**
     * local host
     */
    public final static String LOCALHOST = "0:0:0:0:0:0:0:1";

    /**
     * Main
     * @param args passed in args
     */
    public static void main(String[] args) {
        Socket socket = null;
        InputStream is;
        Reader isr;
        BufferedReader br;
        PrintWriter pw;
        String serverMessage;
        int clientLoopCount = 0;

        Scanner scanner = new Scanner(System.in);

        try {
            while (true) {
                clientLoopCount++;
                System.out.println(Client.class.getName() + " creating socket...");

                socket = new Socket(LOCALHOST, 2317);

                System.out.println("Enter your choice (rock, paper, or scissors):");
                String choice = scanner.nextLine().trim().toLowerCase();

                // Send the choice to the server
                pw = new PrintWriter(socket.getOutputStream(), true);
                pw.println(choice);

                is = socket.getInputStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);

                serverMessage = br.readLine();
                System.out.println("==================================================");

                System.out.println("The message the server sent was: '" + serverMessage + "'");

                Thread.sleep(500L);
            }
        } catch (IOException | InterruptedException e) {
            System.err.println("Problem with " + Client.class.getName() + " networking:");
            System.err.println("Error: " + e);

            if (e instanceof java.net.BindException) {
                System.err.println("*** Be sure to stop any other running instances of programs using this port!");
            }
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                System.err.println("Error closing socket: " + e);
            }

            System.out.println();
            System.out.println(Client.class.getName() + " exit");
        }
    }
}