/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exemploLogging;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ismael
 */
public class ClientLogging {
  public static void main( String[] args ) {
    String hostname= "localhost";
    int port= 5000;
    try {
      switch( args.length ) {
        case 0:
          break;  // use default 
        case 1:
          port = Integer.parseInt(args[0]);
          break;
        case 2:
          hostname = args[0];
          port = Integer.parseInt(args[1]);
          break;
        default:
          System.err.println("Uso: java ClienteLogging [<server-name>] <porta>");
          System.exit(1);
        }
    } catch( NumberFormatException exc ) {
      System.err.println("numero da porta nao e um numero valido!");
      System.exit(2);
    }
    System.out.println("Hostname = " + hostname);
    System.out.println("Parametro porta = " + port);

    Socket server = null;
    try {
      server = new Socket(hostname, port);

      talkToServer(server);

    } catch( UnknownHostException ex ) {
      Logger.getLogger(ClientLogging.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(1);
    } catch( IOException ex ) {
      Logger.getLogger(ClientLogging.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(1);
    }
  }

  private static void talkToServer( Socket server ) {

    PrintWriter out = null;
    BufferedReader in = null;
    try {
      out = new PrintWriter(server.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(server.getInputStream()));
    } catch( IOException ex ) {
      Logger.getLogger(ClientLogging.class.getName()).log(Level.SEVERE, null, ex);
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    String fromServer;
    String fromUser;

    try {
      while( (fromServer = in.readLine()) != null ) {
        System.out.println("Server: " + fromServer);
        if( fromServer.equals("Bye.") ) {
          break;
        }

        fromUser = stdIn.readLine();
        if( fromUser != null ) {
          System.out.println("Client: " + fromUser);
          out.println(fromUser);
        }
      }

      out.close();
      in.close();
      stdIn.close();
      server.close();
    } catch( IOException ex ) {
      Logger.getLogger(ClientLogging.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
