import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class NetworkClient {

	//port number of the server:
	public static final int PORT=12345;
	
	public static void main(String[] args) {
		Scanner keyboard = new Scanner(System.in);
		
		System.out.print("Enter a host name: ");
		String host = keyboard.nextLine();
		
		try (
				//try with resources
				//create a network socket
				Socket sock = new Socket(host, PORT);
				
				//connection is made
				PrintStream outToServer = new PrintStream(
						sock.getOutputStream());
				BufferedReader inFromServer = new BufferedReader(
						new InputStreamReader(sock.getInputStream()));
				
				)
		{
			//try block
			//implement the protocol
			//read from the server
			String reply = inFromServer.readLine();
			System.out.println("Server says: " + reply);
			
			boolean done = false;
			while(!done) {
				//ask for uesr input
				System.out.print("> ");
				String line = keyboard.nextLine();
				
				if(line.equalsIgnoreCase("QUIT")) {
					done = true;
				}
				
				outToServer.println(line);
				outToServer.flush();
				
				reply = inFromServer.readLine();
				System.out.println("Server says: " + reply);
			}
		}
		catch(Exception e) {
			System.err.println(e);
		}
	}

}
