I have the Client program:
class Cliente {
static final String HOST = "localhost";
static final int PUERTO=5000;
public Cliente( ) {
try{
Socket skCliente = new Socket( HOST , Puerto );
InputStream aux = skCliente.getInputStream();/* A partir de aquí no entiendo lo que hace */
DataInputStream flujo = new DataInputStream( aux );
System.out.println( flujo.readUTF() );
skCliente.close(); ... /* Hasta aquí */
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new Cliente();
}
}
And I have the Server program:
class Servidor {
static final int PUERTO=5000;
public Servidor( ) {
try {
ServerSocket skServidor = new ServerSocket(PUERTO); /* A partir de aquí no entiendo lo que hace */
System.out.println("Escucho el puerto " + PUERTO );
for ( int numCli = 0; numCli < 3; numCli++; ) {
Socket skCliente = skServidor.accept(); // Crea objeto
System.out.println("Sirvo al cliente " + numCli);
OutputStream aux = skCliente.getOutputStream();
DataOutputStream flujo= new DataOutputStream( aux );
flujo.writeUTF( "Hola cliente " + numCli );
skCliente.close();... /* Hasta aquí */
}
System.out.println("Demasiados clientes por hoy");
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new Servidor();/* No entiendo para que esta este main aqui? */
}
}
Could you explain to me line by line what each program does?, to better understand the issue of sockets.
Explanation of the client class:
Explanation of the server class:
In both cases it makes use of a wrapper of the data streams
InputStream
andOutputStream
usingDataInputStream
andDataOutputStream
to write strings in UTF-8 usingreadUTF
andwriteUTF
.