import java.io.*;
import java.net.*;

public class ClienteTCP {
  private InetAddress server;
  private Socket sockConn;
  private InputStream rStream;
  private OutputStream wStream;

  public ClienteTCP(String host, int port) 
    throws UnknownHostException, IOException {
    server = InetAddress.getByName(host);
    sockConn = new Socket(server,port);
    rStream = sockConn.getInputStream();
    wStream = sockConn.getOutputStream();

    System.out.println("Conexao: " +
		       server.getHostAddress() +
		       ":" + port);
  }

  public void sendRequest(String request) 
    throws IOException {
    wStream.write(request.getBytes());
    wStream.flush();
    System.out.println("Requisicao: " + request);
  }

  public void showAnswer()
    throws IOException {
    System.out.println("Resposta: ");
    do 
      System.out.print((char) rStream.read());
    while (rStream.available() > 0);
  }

  public void close() 
    throws IOException {
    sockConn.close();
  }

  public static void main(String[] args) {
    try {
      if (args.length < 2) {
	System.err.println("Uso: java ClienteTCP host port");
	System.err.println("     java ClienteTCP host port \"request\"");
	System.exit(1);
      }
      ClienteTCP ch = new ClienteTCP(args[0],Integer.parseInt(args[1]));
      if (args.length > 2)
	ch.sendRequest(args[2] + "\n");
      ch.showAnswer();
      ch.close();
    }
    catch (Exception e) {
      System.err.println(e);
    }
  }
}