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);
    }
}


Learn More :

Socket

    Learn More Multiple Choice Question :