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

public class SocketClient {
  public static void main(String[] args) {

    BufferedReader isw = new BufferedReader(new InputStreamReader(System.in));
    String iLine;

    StringBuffer instr = new StringBuffer();
    System.out.println("-> Jungiamasi prie serverio..");
    
    try {
        System.out.println("Ivesk serverio adresa: ");
        String host = isw.readLine();
        System.out.println("Ivesk porta: ");
        int port = Integer.valueOf(isw.readLine()).intValue();
        
      /** Obtain an address object of the server */
      InetAddress address = InetAddress.getByName(host);
      /** Establish a socket connetion */
      Socket connection = new Socket(address, port);
      System.out.println("-> Prisijungta.");
      
      /** Starting the game.. */
      System.out.println("-> Zaidimas prasideda.");
      int iGuess;
      
      
      BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
      OutputStreamWriter osw = new OutputStreamWriter(bos);
      String process;
      
      BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
      InputStreamReader isr = new InputStreamReader(bis);
      
      do {
          do {
          System.out.print("-> Atspek skaiciu (1 iki 10): ");
          
          iLine = isw.readLine();
          iGuess = Integer.parseInt(iLine);
          } while ((iGuess < 1) || (iGuess > 10));  
      
          
          process = "" + iGuess +  (char) 0;
          osw.write(process);
          osw.flush();

          int c;
          instr.delete(0, instr.length());
          while ( (c = isr.read()) != 0)
             instr.append( (char) c);
      
          if (instr.toString().equals("1")) {
               System.out.print("Atspejai. Zaisti dar? [T/N] "); 
               System.out.println("");
               
               iLine = isw.readLine();
               
               if (iLine.equals("T") || iLine.equals("t")) {
                   /** For to continue playing */
                    instr.delete(0, instr.length());
                    instr.append("0");
          
                    process = "T" + (char) 0;
                    osw.write(process);
                    osw.flush();  
               }
          } else {
             System.out.println("Neatspejai. Bandyk dar karta");
          }
      } while (!instr.toString().equals("1"));
      
      
      process = "N" + (char) 0;
      osw.write(process);
      osw.flush();  
      
      System.out.println("-> Zaidimas baigia darba..");
      connection.close();
     }
    catch (IOException f) {
      System.out.println("IOException: " + f);
    }
    catch (Exception g) {
      System.out.println("Exception: " + g);
    }
  }
}