import java.io.*;
import java.net.*;

public class TcpClient2 {
  public static final int DEFAULT_PORT = 6789;
  public static void usage() {
    System.out.println("Usage: java C2 <serverhost>");
    System.exit(0);
  }
  
  public static void main(String[] args) {
    int port = DEFAULT_PORT;
    String address = "";
    Socket s = null;
    int end = 0;
// parse the port specification
    if ((args.length != 0) && (args.length != 1)) usage();
    if (args.length == 0) {
      port = DEFAULT_PORT;
      address = "localhost";
    } else {
      address = args[0];
    }
    try {
      PrintWriter writer;
      BufferedReader reader;
      BufferedReader kbd;
// create a socket to communicate to the specified host and port
      s = new Socket(address, port);
// create streams for reading and writing
      reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
      OutputStream sout = s.getOutputStream();
      writer = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
// create a stream for reading from keyboard
      kbd = new BufferedReader(new InputStreamReader(System.in));
// tell the user that we've connected
      System.out.println("Connected to " + s.getInetAddress() +
        ":" + s.getPort());
      String line;
// read the first response (a line) from the server
      line = reader.readLine();
// write the line to console
      System.out.println(line);
      while (true) {
// print a prompt
        System.out.print("> ");
        System.out.flush();
// read a line from console, check for EOF
        line = kbd.readLine();
        if (line.equals("Server Exit")) end = 1;
// send it to the server
        writer.println(line);
        writer.flush();
// read a line from the server
        line = reader.readLine();
// check if connection is closed, i.e., EOF
        if (line == null) {
          System.out.println("Connection closed by server.");
          break;
        }
        if (end == 1) {
          break;
        }
// write the line to console
        System.out.println("Server says: " + line);
      }
      reader.close();
      writer.close();
    }
    catch (IOException e) {
      System.err.println(e);
    }
// always be sure to close the socket
    finally {
      try {
        if (s != null) s.close();
      }
      catch (IOException e2) { }
    }
  }
}