package echo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Connects to an echo server, sends each line typed at the keyboard, and prints
 * the reply. Arguments: host and port (default localhost 6000).
 */
public class EchoClient {

	public static void main ( String[] args ) {
		String host = "localhost";
		int port = EchoServer.PORT;
		if ( args.length >= 2 ) {
			host = args[0];
			port = Integer.parseInt(args[1]);
		}

		try {
			Socket socket = new Socket(host,port); // connects, or throws
			BufferedReader in =
			    new BufferedReader(new InputStreamReader(socket.getInputStream(),
			                                             StandardCharsets.UTF_8));
			PrintWriter out =
			    new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),
			                                           StandardCharsets.UTF_8));
			Scanner keyboard = new Scanner(System.in);

			System.out.println("connected to " + host + ":" + port
			    + " from local port " + socket.getLocalPort());
			for ( ; keyboard.hasNextLine() ; ) {
				String line = keyboard.nextLine();
				out.println(line);
				out.flush(); // send it now

				String reply = in.readLine(); // wait for the answer
				if ( reply == null ) {
					System.out.println("the server closed the connection");
					break;
				}
				System.out.println(reply);
				if ( reply.equals("bye") ) {
					break;
				}
			}
			socket.close();
		} catch ( IOException e ) {
			System.out.println("can't talk to " + host + ":" + port + ": "
			    + e.getMessage());
		}
	}

}
