Skip to content
Snippets Groups Projects
SchnitzlerClient.java 2.20 KiB
package MV3500Cohort2024JulySeptember.homework2.Schnitzler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Homework2: Client which connect to a server and prints all incoming messages of the server to the console.
 * 
 * @author simonschnitzler
 */
public class SchnitzlerClient {
    
    /** Default constructor */
    public SchnitzlerClient(){
        // default constructor
    }
    
    /** IPv6 String constant for localhost address, similarly IPv4 127.0.0.1
     * @see <a href="https://en.wikipedia.org/wiki/localhost" target="_blank">https://en.wikipedia.org/wiki/localhost</a>
     * @see <a href="https://en.wikipedia.org/wiki/IPv6_address" target="_blank">https://en.wikipedia.org/wiki/IPv6_address</a> 
     */
    public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; //Local host

    /**
     * Program invocation, execution starts here
     * @param args the command line arguments
     * @throws java.lang.Exception if connection failed
     */
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket(LOCALHOST, 2317);

        Thread connection = new Thread(new Reader(socket));
        connection.start();

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine() && connection.isAlive()) {
            out.println(scanner.nextLine());
        }
    }

    private static class Reader implements Runnable {
        private BufferedReader in;
        private final Socket socket;

        public Reader(Socket socket) throws IOException {
            this.socket = socket;
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        }

        @Override
        public void run() {
            try (socket){
                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println(message);
                }
            } catch (IOException e) {
                System.out.println("Error reading from server: " + e);
            }
        }
    }
    
}