import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * A client that can connect to the knock-knock server. 
 *
 * @author Matt Boutell, from the Sun Java Tutorial.
 *         Created Oct 15, 2006.
 */
public class KnockKnockClient {

	/**
	 * Execution starts here.
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		String hostName = "localhost";
		Socket server = null;
		try {
			server = new Socket(hostName, 4321);
		} catch (UnknownHostException exception) {
			System.out.println("Couldn't find the given hostname: " + hostName);
			exception.printStackTrace();
		} catch (IOException exception) {
			exception.printStackTrace();
		}
		
		// Input and output streams
		PrintWriter toServer = null;
		Scanner fromServer = null;
		Scanner scanner = null;

		try {
			// We write to the client using its output stream. The second argument
			// means that output is flushed, rather than buffered.
			toServer = new PrintWriter(server.getOutputStream(), true);
	
			// We read input from the client using its input stream.
			fromServer = new Scanner(server.getInputStream());
	
			String fromServerLine, userLine;
			scanner = new Scanner(System.in);
	
			while (fromServer.hasNext()) {
				fromServerLine = fromServer.nextLine();
				System.out.println("Server: " + fromServerLine);
				if (fromServerLine.equals("Bye."))
					break;
				if (scanner.hasNext()) {
					userLine = scanner.nextLine();
					System.out.println("Client: " + userLine);
					toServer.println(userLine);
				}
			}
		
			// Close the streams
			fromServer.close();
	        toServer.close();
	        scanner.close();
	        
	        // Close the socket.
	        server.close();
		} catch (IOException exception) {
			exception.printStackTrace();
		}

	}
}