Creates a class that compresses the file that is inputted

How to write a Java Program to Creates a class that compresses the file that is in-putted ?


Solution:

//Creates a class that compresses the file that is inputted
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Compress {
 //Creates a static int type to store the default ASCII values that will be appended
 static int defaultValues = 256;
 //Creates a variable that reads the current byte in the file
 int readByte = 0;
 //Creates a constant int type to store the size of the dictionary/hash table
 final static int MAX_TABLE_SIZE = 4096;
 public static void main (String[] args) throws IOException
 {
   
  String key = "";
  //Creates a new Dictionary and initializes it with the set size
  Dictionary newDict = new Dictionary(MAX_TABLE_SIZE);
  //String stringValue  = new Character((char)).toString();
  int readByte;
  MyOutput fileOut = new MyOutput();
  int appendCode = 256;
  String inputFile = args[0];
  String outputFile = inputFile + ".zzz";
  try
  {
   BufferedInputStream in;
   in = new BufferedInputStream(new FileInputStream(inputFile));
   BufferedOutputStream out;
   out = new BufferedOutputStream(new FileOutputStream(outputFile));
   for (int i = 0; i < defaultValues; i++)
   {
    String stringValue2  = new Character((char)i).toString();
    DictEntry newEntry = new DictEntry(stringValue2, i);
    newDict.insert(newEntry);
   } 
   readByte=in.read();
   String appendString = "";
   //String value = new Character((char)readByte).toString();
   while (in.read()!=-1) //&& newDict.find(appendString).equals(null))
   {
    String value = new Character((char)readByte).toString();
    appendString += value;
    //appendString += (char)readByte;
    /*if (readByte == -1)
    {
     System.out.println("");
     break;
    }*/
    if (newDict.find(appendString) == null || newDict.find(appendString).equals(null))
    {
     //appendString += value;
     DictEntry newString = new DictEntry(appendString, appendCode);
     if (newDict.numElements() < MAX_TABLE_SIZE)
     {
      newDict.insert(newString);
     }
     appendCode++;
     //appendString += (char)readByte;//Integer.toString(appendCode);
     //fileOut.output(appendCode, out);
     //appendString = "";
     fileOut.output(appendCode, out); //outputkey
     appendString = "";
     //System.out.print(newDict.find(appendString).getCode());
    }
    else {
     key = appendString;
     readByte = in.read();
    }
    appendString = value;
    //readByte = in.read();
   }
   //readByte = in.read();
   fileOut.output(appendCode, out);//out put key again
   //fileOut.flush(out);
   if (in != null)
   {
    in.close();
   }
   //fileOut.flush(out);
   if (out != null)
   {
    out.close();
   } 
   fileOut.flush(out);
  }
  catch (DictionaryException e)
  {
   System.out.println("error");
  }
 }

}

Java Rock Paper Scissors


//Import Scanner
import java.util.Scanner;
import java.util.Random;
public class PaperScissorsRock
{
        public static void main(String[] args)
        {
             //Title
             System.out.println("Rock, Paper, Scissors");
             //Scanner
             Scanner sc = new Scanner(System.in);
             //Insert Values
             System.out.print("Enter 0 for paper, 1 for scissors, or 2 for rock (-1 to quit): ");
             int Value1 = sc.nextInt();
             //Randomizer
             Random randomGen = new Random();
             // nextInt() returns a pseudo random, uniformly
             // distributed integer value between 0 (inclusive)
             // and the specified value (exclusive), therefore,
             // the following generates a random value between 0 to 2
             int Value2 = randomGen.nextInt(3);
             //Computer Output
             switch(Value2)
             {
             case 0:
             System.out.println("Computer picks paper");
             break;
             case 1:
                System.out.println("Computer picks scissors");
                break;
             case 2:
             System.out.println("Computer picks rock");
                break;
             }
             //Calculation
             if (Value1 >= 0){
                if ((Value1 == 0 && Value2 == 2) || (Value1 == 1 && Value2 == 0) || (Value1 == 2 && Value2 == 1))
                      System.out.println("Player Wins");
                if ((Value1 == 0 && Value2 == 0) || (Value1 == 1 && Value2 == 1) || (Value1 == 2 && Value2 == 2))
                    System.out.println("Draw");   
             else 
             System.out.println("Computer Wins");
             }
         //Error
         if (Value1 < 0)
              System.out.println("Invalid input.");
             //Output
         }
}

JAVA Leap Year WIP


//Import Scanner
import java.util.Scanner;
public class LeapYears
{
        public static void main(String[] args)
        {
                    //Title
                    System.out.println("Leap Year Calculation");
                //Scanner
                Scanner sc = new Scanner(System.in);
                //Insert Values
                System.out.print("Enter The Year: ");
                int Year = sc.nextInt();
                //Calculation
                int LeapYear = Year % 4;
                int LeapYear2 = Year % 100;
                int LeapYear3 = Year % 400;
                //Output
                if (LeapYear > 0)
                 if ((LeapYear == 0 && LeapYear2 != 0) || LeapYear3 == 0)
                 {
                       System.out.println(Year + " is a leap year");
                          System.out.println("The numbers of days in" + Year + "is 366.");
                }
                else {
                       System.out.println(Year + " is NOT a leap year");
                       System.out.println("The numbers of days in" + Year + "is 365.");         
                }
                //Output Invalid
                if (Year <= 0) {
                 System.out.println("Invalid Input");
                }
                //Closing
                }

Java Weight Program


//Import Scanner
import java.util.Scanner;
public class WeightProgram
{
        public static void main(String[] args)
        {
             //Title
             System.out.println("Weight Program ");
                //Scanner
                Scanner sc = new Scanner(System.in);
                //Insert Apple
                System.out.print("Enter the number of apple to buy: ");
                int AppleAmount = sc.nextInt();
                //Insert Mango
                System.out.print("Enter the number of mango to buy: ");
                int MangoAmount = sc.nextInt();
                //Default Weight
                int AppleWeight = 103;
                int MangoWeight = 110;
                //TotalWeight
                int TotalWeight = (AppleAmount * AppleWeight) + (MangoAmount * MangoWeight);
                //Calculation
                int G100 = TotalWeight / 100;
                int G50 = TotalWeight %100 /50;
                int G20 = TotalWeight %100 /20;
                int G10 = TotalWeight %100 %20 /10;
                int G5 = TotalWeight %100 %20 %10 /5 ;
                int G1 = TotalWeight %10 %20 %10 %5 /1;
                System.out.println("100g-weight:" + G100);
                System.out.print(" ");
                System.out.println("50g-weight:" + G50);
                System.out.print(" ");
                System.out.println("20g-weight:" + G20);
                System.out.print(" ");
                System.out.println("10g-weight:" + G10);
                System.out.print(" ");
                System.out.println("5g-weight:" + G5);
                System.out.print(" ");
                System.out.println("1g-weight:" + G1);
                System.out.print(" ");
        }
}

Java QuadraticCalculator


//Import Scanner
import java.util.Scanner;
public class QuadraticCalculator
{
        public static void main(String[] args)
        {
             //Title
             System.out.println("Welcome to use Quadratic Calculator ");
                //Scanner
                Scanner sc = new Scanner(System.in);
                //Insert Values  
                System.out.print("Pleast enter the value a: ");
                double ValueA = sc.nextDouble();
                System.out.print("Pleast enter the value b: ");
                double ValueB = sc.nextDouble();
                System.out.print("Pleast enter the value c: ");
                double ValueC = sc.nextDouble();
                //Disciminant
                double Disc = (ValueB * ValueB) - (4 * ValueA * ValueC);
                double QuadFormPlus = (-ValueB + Math.sqrt(Disc)) / (2 * ValueA);
                double QuadFormMinus = (-ValueB - Math.sqrt(Disc)) / (2 * ValueA);
                double QuadFormZero = -ValueB / (2 * ValueA);
                //Result more than zero
                if (Disc > 0) {
                 System.out.println("");
                }
                System.out.println("X1:" + QuadFormPlus);
                System.out.println("X2:" + QuadFormMinus);
                //Result equals zero
                if (Disc == 0) {
                 System.out.println("X:"+ QuadFormZero);
                }
                //Math Error
                if (Disc < 0) {
                 System.out.println("Math Error");
                }
        }
}

Java CaylinderCal



//Import Scanner
import java.util.Scanner;
public class CylinderCal 
{
 public static void main(String[] args)
 {
  //Scanner
  Scanner sc = new Scanner(System.in);
  System.out.print("Please enter the radius: ");
  //insert radius
  double Radius = sc.nextDouble();
        System.out.print("Please enter the height: ");
  //insert height
  double Height = sc.nextDouble();
  //Surface Area
  double Result1 = 2 * Math.PI * Radius * Height;
  System.out.println("The surface area is " + Result1);
  //Volume
  double RadiusSquare = Radius * Radius;
  double Result2 = Math.PI * RadiusSquare * Height;
  System.out.println("The Volume is " + Result2);
 }
}

JAVA SeperateDigit

//Import Scanner
import java.util.Scanner;
public class SeperateDigit
{
 public static void main(String[] args)
 {
  //Scanner
  Scanner sc = new Scanner(System.in);
  System.out.print("Please enter the five numbers interger (00000-99999): ");
  //insert five number interger.
  int Inter = sc.nextInt();
  int Dig1 = Inter / 10000;
  int Dig2 = Inter % 10000 / 1000;
  int Dig3 = Inter % 1000 / 100;
  int Dig4 = Inter % 100 / 10;
  int Dig5 = Inter % 10;   
  //calculation
     System.out.print("Digits in Interger are " + Dig1);
     System.out.print(" " + Dig2);
     System.out.print(" " + Dig3);
     System.out.print(" " + Dig4);
     System.out.print(" " + Dig5);
 }
}

Java Read / Write Text file

How to write a Java Program to Java Read / Write Text file ?


Solution:


private String readTextFile(String filePath) {
    StringBuilder str = new StringBuilder("");
    try {
        FileInputStream fips = new FileInputStream(filePath);
        InputStreamReader ipsReader = new InputStreamReader(fips, "UTF-8");
        int character;
        while ((character = ipsReader.read()) != 1) {
            str.append((char) character);
        }
        ipsReader.close();
    } catch (FileNotFoundException ex) {
        // may happen during file IO mapping
        System.out.println(ex.getCause().getMessage());
    } catch (UnsupportedEncodingException ex) {
        // may happen during load unsupported charset file
        System.out.println(ex.getCause().getMessage());
    } catch (IOException ex) {
        // may happen during read file
        System.out.println(ex.getCause().getMessage());
    }
    return str.toString();
}

private void writeTextFile(String filePath, String content) {
    try {
        FileOutputStream fops = new FileOutputStream(filePath);
        OutputStreamWriter opsWriter = new OutputStreamWriter(fops, "UTF-8");
        opsWriter.write(content);
        opsWriter.close();
    } catch (FileNotFoundException ex) {
        // may happen during file IO mapping
        System.out.println(ex.getCause().getMessage());
    } catch (UnsupportedEncodingException ex) {
        // may happen during load unsupported charset file
        System.out.println(ex.getCause().getMessage());
    } catch (IOException ex) {
        // may happen during read file
        System.out.println(ex.getCause().getMessage());
    }
}

Calculates the average, minimum, maximum, median, and standard deviation of the scores

How to write a java program to calculates the average, minimum, maximum, median, and standard deviation of the scores ?


Solution:


import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
/*This project calculates the average, minimum, maximum, median, and standard deviation of the scores. */
public class ScoreCalculator3
{
   public static void main(String[] args)
   {    
       Scanner in = new Scanner(System.in); // declare and create a Scanner object which will read user input from keyboard
       
       int scores[] = new int[100];
       int answer;
       
        do
        {
            double input;
            int numScores = 0;
            double sum = 0;
            double average = 0.0;
            double min = 100;
            double max = 0;
            double median = 0;
            double stdev = 0;
            System.out.println("Please enter scores on a single line and type a -1 at the end ");
            input = in.nextDouble();
            
             if (input == -1) {
                System.out.println( "Number of scores  : 0");
                System.out.println("The average score  : 0.00");
                System.out.println("The minimum score  : 0");
                System.out.println("The maximum score  : 0");
                System.out.println("The median         : 0");
                System.out.println("The standard deviation: 0");
                answer = JOptionPane.showConfirmDialog(null, "Do you want to continue?"); 
                in.nextLine();
                continue;
            }

            while (input != -1) {
                // Add input to scores array
                scores[numScores] = (int)input;
                
                // Increment numScores
                numScores++;
                input = in.nextDouble();
            }
            in.nextLine();
            //average = (double)(sum/(double)numScores);
            
            numScores = loadArray(scores);
            
            // Print output
            System.out.println("Number of scores   : " + loadArray(scores));
            System.out.printf("The average score: %.2f\n", findAverage(scores, numScores));
            System.out.println("The minimum score  : " + findMinimum(scores, numScores));
            System.out.println("The maximum score  : " + findMaximum(scores, numScores));
            System.out.println("The median score  : " + findMedian(scores, numScores));
            System.out.println("The standard deviation : " + findSTD(scores, numScores, findAverage(scores, numScores)));   

            answer = JOptionPane.showConfirmDialog(null, "Do you want to continue?");
        } while (answer == 0);
       
       
   }
   public static int loadArray(int[] arr) // load array
   {    
       int length = 0;
       for (int i = 0; i < 100; i++) {
           if (arr[i] != -1) {
               length++;
               
           } else{ 
               break;
           }
       }
       
       return length;
   }

   /**
    * Compute the average scores
    * @param arr 
    * @param numberOfScores 
    * @return average
    */
   public static double findAverage(int[] arr, int numberOfScores)
   {
       int sum = 0;
       for (int i = 0; i < numberOfScores; i++) {
           sum = sum + arr[i];
       }
       return sum / numberOfScores;
   }
   /**
    * Compute the minimum scores for that courses
    * @param arr
    * @param numberOfScores
    * @return minimum
    */
   public static int findMinimum(int[] arr, int numberOfScores) 
   {
       int min = 100;
       for (int i = 0; i < numberOfScores; i++) {
           // If element is lesser than min
           if (arr[i] < min) {
               // Declare new min
               min = arr[i];
            }
        }
        return min;
   }
   /**
    * Compute the maximum scores for that courses
    * @param arr
    * @param numberOfScores
    * @return maximum
    */
   public static int findMaximum(int[] arr, int numberOfScores)
   {
       int max = 0;
       for (int i = 0; i < numberOfScores; i++) {
           // If element is more than max
           if (arr[i] > max) {
               // Declare new max
               max = arr[i];
            }
        }
        return max;
   }
   /**
    * Compute the standard deviation for that courses
    * @param arr
    * @param numberOfScores
    * @param avg
    * @return STD
    */
   public static double findSTD(int[] arr, int numberOfScores, double avg)
   {
       double sum_diff = 0;
       for (int i = 0; i < numberOfScores; i++) {
           sum_diff = sum_diff + Math.pow(arr[i] - avg, 2);
       }
       return Math.sqrt(sum_diff / numberOfScores);
   }
   /**
    * Compute median scores for that courses
    * @param arr
    * @param numberOfScores
    * @return median
    */
   public static double findMedian(int[] arr, int numberOfScores) 
   {
      Arrays.sort(arr); 
      
      // If even number of scores
      if (numberOfScores % 2 == 0) {
          int mid = numberOfScores / 2;
          return (arr[mid-1] + arr[mid])/2;
      }
        // If odd number of scores
        else {
            int mid = numberOfScores / 2;
            return arr[mid];
        }
      
      /*
      int mid = arr.length/2;
      if (arr.length%2 == 1) {
          return arr[mid];
      } else
      {
          return (arr[mid-1] + arr[mid]) / 2.0;
      }
      */
          
        
   }
   public static void printArray(int[] arr, int length) 
   {
       for (int i =0; i < length; i++)
       {
           System.out.print(arr[i] + " ");
       }
       System.out.println(); 
   }
}

Ejemplo Socket Server Java Program

How to write a Ejemplo Socket Server Java Program ?


package redessocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lopez, Mariano
 */
public class SocketServer {
     ServerSocket server = null;
     //array de clientes
     ArrayList<SocketInfo> clientes;
     public SocketServer(int port) throws IOException{
         this.server = new ServerSocket(port);
         this. clientes = new ArrayList<>();
     }
    
     public void listen() throws IOException{
         //escuchar comandos por teclado
         escucharComandosServer();
         //si se logro instanciar.. mientras que no este cerrado el socket
        while(server != null && !server.isClosed()){
            Socket clientSocket = null;
            try {
               //escucha de peticiones 
               clientSocket = server.accept();
               if(clientSocket != null){
                   lanzarHilo(clientSocket);
               }
            }catch (IOException e){System.out.println(e.toString());}
        }
     }
     public static void main(String[] args) {
        System.out.println("Socket Server - Redes de datos 2015 - Lopez, Mariano");
        BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Ingrese el puerto para inicializar el servidor: ");
         try {
             int port = Integer.parseInt(entrada.readLine());
             SocketServer server = new SocketServer(port);
             System.out.println("Inicialización correcta! puerto: "+port+"\nLISTENING");
             server.listen();
         } catch (IOException ex) {
             System.out.println(ex.toString());
         }catch(NumberFormatException fe){
             System.out.println(fe.toString());
         }
    }
    //comandos que se pueden ejecutar solo en el servidor 
    private void escucharComandosServer() throws IOException{
        BufferedReader entradaDesdeUsuario = new BufferedReader(new InputStreamReader(System.in));
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean flag_fin = true;
                while(flag_fin){
                    try {
                        if(entradaDesdeUsuario.ready()){
                            String in =entradaDesdeUsuario.readLine();
                            switch(in){
                                case "exit":
                                    System.out.println("Shooting down...");
                                    KillEmAll();
                                    server.close();
                                    flag_fin=false;
                                    break;
                                case "who":
                                    System.out.println(clientesInfo());
                                    break;
                                default:
                                    System.out.println("Comandos:\nwho\t\tInformación sobre clientes conectados\nexit\t\tFinalizar todas las conexiones y cerrar el socket\n");
                                    break;
                            }
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });
       t.start();
    }
    //hilo para atender a cada socket cliente
    private void lanzarHilo(Socket clientSocket){
        SocketInfo socket_info = new SocketInfo(clientSocket);
        clientes.add(socket_info);
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //string para almacenar mensajes del cliente
                    String line;
                    //ip del cliente
                    String ip = clientSocket.getInetAddress().toString();
                    //puerto del cliente
                    int puerto = clientSocket.getPort();
                    System.out.println("Nuevo cliente: "+ip+":"+puerto);
                    //output stream para escritura con el cliente
                    DataOutputStream salidaACliente = new DataOutputStream(clientSocket.getOutputStream());
                    //stream para lectura del cliente
                    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                    //mientras este conectado
                    while (!clientSocket.isClosed()) {
                        //leer desde el stream del cliente
                        line = readStringUTF(in);
                        System.out.println("\nCliente: "+ip+":"+puerto+"\n"+line);
                        //en la linea 0 esta el comando a ejecutar
                        line = (line.split("\n"))[0];
                        //si el mensaje es exit -> cerrar conexión
                        if(line.equals("exit")){
                            System.out.println("El cliente: "+ip+":"+puerto +" ha solicitado cierre");
                            clientes.remove(socket_info);
                            clientSocket.close();
                            break;
                        }else{
                            //todas las acciones que puede realizar el servidor
                            acciones(line, salidaACliente,socket_info);
                        }
                    }//fin while 
                    //cerrar stream
                    in.close();
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                } 
            }//end run
        });
        t.start();
    }
    //comandos que pueden realizar los clientes
    private void acciones(String in,DataOutputStream salidaACliente,SocketInfo socket_info) throws IOException{
        //historial de solicitudes
        socket_info.addToHistory(in);
        switch(in){
            case "cores":
                respuesta(salidaACliente, 200, "Procesadores disponibles para JVM (cores): " +Runtime.getRuntime().availableProcessors());
                break;
            case "ram -free":
                respuesta(salidaACliente, 200, "Memoria libre para JVM: " + Runtime.getRuntime().freeMemory()+"Bytes");
                break;
            case "ram -total":
                respuesta(salidaACliente, 200, "JVM total de memoria: " +Runtime.getRuntime().totalMemory()+"Bytes");
                break;   
            case "ram -max":
                respuesta(salidaACliente, 200, "Maxima cantidad de RAM que puede llegar a usar la JVM: " +Runtime.getRuntime().maxMemory()+"Bytes");
                break;
             case "so -name":
                respuesta(salidaACliente, 200, "Sistema Operativo: "+System.getProperty("os.name"));
                break;  
            case "history":
                respuesta(salidaACliente, 200, socket_info.getHistory());
                break; 
             case "help":
                 String aux = "Lista de comandos\n"
                         + "cores\t\tProcesadores disponibles para JVM\n"
                         + "ram -free\t\tMemoria libre para JVM\n"
                         + "ram -total\t\tJVM total de memoria\n"
                         + "ram -max\t\tMaxima cantidad de RAM que puede llegar a usar la JVM\n"
                         + "so -name\t\tSistema Operativo\n"
                         + "history\t\tHistorial de comandos\n"
                         + "exit\t\tterminar conexión\n";
                respuesta(salidaACliente, 200, aux);
                break; 
            default:
                respuesta(salidaACliente, 400, "Comando no reconocido");
                break;
                
        }
                            
    }
    //finaliza todas las conexiones existentes ... tambien es el primer disco de Metallica.
    private void KillEmAll() throws IOException{
        for(SocketInfo s:clientes){
            s.getSocket().close();
        }
    }
    //String con información de los clientes online
    private String clientesInfo(){
        String retorno = "Cantidad de clientes online: "+clientes.size()+"\n";
        retorno+="Socket información(IP, puerto remoto y puerto local) \t Fecha de la conexión\n";
        for(SocketInfo s:clientes){retorno+=s.showInfo();}
        return retorno;
    }
    //escribir cabecera + respuesta en el DataOutputStram para el cliente
    private void respuesta(DataOutputStream salidaACliente,int code, String mensaje) throws IOException{
        String estado = "";
        switch(code){
            case 200:
                estado="OK";
                break;
            case 400:
                estado="Bad request";
                break;
            case 500:
                estado="Internal Error";
                break;
                default:
                    estado="OK";
                    break;
        }
        Date fecha = new Date();
        String aux = code+" "+estado+"\nDate: "+fecha+"\nContent-Type: text charset=UTF-8\nContent-Length: "+mensaje.length()+"\n\n"+mensaje+"\n";
        byte[] data=aux.getBytes("UTF-8");
        salidaACliente.writeInt(data.length);
        salidaACliente.write(data);
    }
    private static String readStringUTF(DataInputStream in) throws IOException{
        int length=in.readInt();
        byte[] data=new byte[length];
        in.readFully(data);
        return new String(data,"UTF-8");
    }
    //clase auxiliar para guardar atributos
    private class SocketInfo{
        private Socket socket;
        private Date fecha;
        private String history;
        private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        
        public SocketInfo(Socket s){
            this.socket = s;
            this.fecha = new Date();
            this.history="Historial de comandos:\n";
        }
        public void addToHistory(String s){
            this.history+=s+"\t"+dateFormat.format(new Date())+"\n";
        }
        public String getHistory(){
            return this.history+"\n******************************************************************";
        }
        public Socket getSocket(){
            return this.socket;
        }
        public Date getFechaConexion(){
            return this.fecha;
        }
        public String showInfo(){
            return this.getSocket().toString()+"\t"+dateFormat.format(this.getFechaConexion())+"\n"+this.getHistory()+"\n\n";
        }
    }
}

Ejemplo Socket Cliente Java Program

How to write a Ejemplo Socket Cliente in Java Program ?


package redessocket;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author Lopez, Mariano
 */
import java.io.*;
public class SocketCliente {
    public static void main(String[] args) {
        System.out.println("Socket Cliente - Redes de datos 2015 - Lopez, Mariano");
        try {
            String frase;
            //buffer para almacenar la entrada por teclado
            BufferedReader entradaDesdeUsuario = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Ingrese la IP y el puerto (ip:puerto) para conectar el socket: ");
            //lectura del teclado, particion del string dejando en la posición 0 la ip y en la 1 el puerto
            String[] aux = (entradaDesdeUsuario.readLine()).split(":");
            //inicialización del socket
            Socket socketCliente = new Socket(aux[0], Integer.parseInt(aux[1]));
            System.out.println("Inicialización correcta! IP:puerto: "+aux[0]+":"+aux[1]);
            //stream para comunicar con el socket server
            DataOutputStream salidaAServidor = new DataOutputStream(socketCliente.getOutputStream());
            //stram para leer al server
            DataInputStream inn = new DataInputStream(socketCliente.getInputStream());
            //mientras este abierta la conexión
            while(!socketCliente.isClosed()){
                //leer comando por teclado
                frase = entradaDesdeUsuario.readLine();
                //si el comando fue exit finaliza el while e informa salida al server
                if(frase.equals("exit")){
                    //envio al servidor
                    //salidaAServidor.writeBytes(frase + "\n");
                    enviar(salidaAServidor, frase);
                    break;
                }else{
                    //envio al servidor
                    enviar(salidaAServidor, frase);
                    //salidaAServidor.writeBytes(frase + "\n");
                    //imprimir lo que responde el servidor (requiere conversión)
                    System.out.println(readStringUTF(inn));
                } 
            }
            //cerrar socket
            socketCliente.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }catch(NumberFormatException fe){
            System.out.println(fe.toString());
        }
    } 
    //retornar String formato UTF-8 a partir de un inputStram
    private static String readStringUTF(DataInputStream in) throws IOException{
        int length=in.readInt();
        byte[] data=new byte[length];
        in.readFully(data);
        return new String(data,"UTF-8");
    }
    private static void enviar(DataOutputStream salidaAServidor,String mensaje) throws IOException{
        String estado = "";
        String aux = mensaje+"\nUser-Agent: "+System.getProperty("os.name")+"\n";
        byte[] data=aux.getBytes("UTF-8");
        salidaAServidor.writeInt(data.length);
        salidaAServidor.write(data);
    }
}