You are on page 1of 5

LABORATORIO No.

1
FUNDAMENTOS EN SISTEMAS DISTRIBUIDOS
COMUNICACIÓN ENTRE PROCESOS CON SOCKETS1

PARTE 1. Sockets usando UDP

1. Se entrega a usted el código fuente de un ejemplo sencillo sobre comunicación entre procesos usando
sockets con el protocolo UDP.

Código del lado cliente


package Cliente;

import java.net.*;
import java.io.*;
public class UDPCliente{
public static void main(String args[]){
// Los argumentos dan el contenido del mensaje y dirección Servidor
DatagramSocket unSocket = null;
try {
unSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress dirServ = InetAddress.getByName(args[1]);
int puertoServ = 7001;
DatagramPacket peticion =
new DatagramPacket(m, args[0].length(), dirServ, puertoServ);
unSocket.send(peticion);
byte[] buffer = new byte[1000];
DatagramPacket respuesta = new DatagramPacket(buffer, buffer.length);

unSocket.receive(respuesta);
System.out.println("Le devuelvo en este ejercicio de sockets: " + new
String(respuesta.getData()));
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e){System.out.println("IO: " + e.getMessage());
}finally {if(unSocket != null) unSocket.close();}
}
}

Código del lado servidor


package Servidor;
import java.net.*;
import java.io.*;
public class UDPServidor{
public static void main(String args[]){
DatagramSocket unSocket = null;
try{
unSocket = new DatagramSocket(7001);
// crea un socket en el puerto acordado
byte[] buffer = new byte[10000];
while(true){
DatagramPacket peticion = new DatagramPacket(buffer,
buffer.length);
unSocket.receive(peticion);
DatagramPacket respuesta = new DatagramPacket(peticion.getData(),
peticion.getLength(),
peticion.getAddress(), peticion.getPort());
unSocket.send(respuesta);
}
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
}catch (IOException e) {System.out.println("IO: " + e.getMessage());
}finally {if(unSocket != null) unSocket.close();}
}
}

1 Tomado del libro “Sistemas Distribuidos” de George Coulouris y otros


Se le solicita:
• Documentar el código línea a línea indicando que se instruye a la máquina en cada una
de ellas.
• Compilar y ejecutar el proceso servidor en una máquina y el proceso cliente en otra
máquina; logrando obtener el resultado esperado de acuerdo a lo explicado por el docente
en la sesión de clase. Debe presentar, en la siguiente sesión, la ejecución lograda a su
profesor de la asignatura y contestar a las preguntas que éste le haga sobre el proceso
seguido por usted(es) para lograr el resultado.
• La frase a utilizar para que el servidor responda repitiéndola será: Esta frase va desde el
cliente al servidor y regresa, es un servidor ECO.

2. Varíe el proceso servidor de tal manera que solo acepte mensajes de tamaño veinte “bytes”; pruebe a
enviar el mensaje anterior y explique lo que sucede.

PARTE 2. Sockets usando TCP (Streams)

1. Se entrega a usted el código fuente de un ejemplo sencillo sobre comunicación entre procesos
usando sockets con el protocolo TCP.

Código del lado cliente


package Cliente;
import java.net.*;
import java.io.*;
public class TCPCliente {
public static void main (String args[]) {
Socket s = null;
try{
int puertoServicio = 7800;
s = new Socket(args[1], puertoServicio);
DataInputStream entrada = new DataInputStream( s.getInputStream());
DataOutputStream salida =new DataOutputStream( s.getOutputStream());
salida.writeUTF(args[0]);
String datos = entrada.readUTF();
System.out.println("El servidor hace eco de: "+ datos) ;
}catch (UnknownHostException
e){System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
}catch (IOException e){System.out.println("Linea leida:"+e.getMessage());
}finally {if(s!=null) try {s.close();}catch (IOException
e){System.out.println("cerrar:"+e.getMessage());}}
}
}

Código del lado servidor


package Servidor;
import java.net.*;
import java.io.*;
public class TCPServidor {
public static void main (String args[]) {
try{
int puertoServ = 7800;
ServerSocket escuchaSocket = new ServerSocket(puertoServ);
while(true) {
Socket clienteSocket = escuchaSocket.accept();
Conexion c = new Conexion(clienteSocket);
}
} catch(IOException e) {System.out.println("Socket a la escucha o
servidor:"+e.getMessage());}
}
}
class Conexion extends Thread {
DataInputStream entrada;
DataOutputStream salida;
Socket clienteSocket;
public Conexion (Socket aClienteSocket) {
try {
clienteSocket = aClienteSocket;
entrada = new DataInputStream( clienteSocket.getInputStream());
salida =new DataOutputStream( clienteSocket.getOutputStream());
this.start();
} catch(IOException e) {System.out.println("Conexion:"+e.getMessage());}
}
public void run(){
try {

String datos = entrada.readUTF();


salida.writeUTF(datos);
}catch (EOFException e){System.out.println("EOF:"+e.getMessage());
} catch(IOException e) {System.out.println("Linea leida:"+e.getMessage());
} finally{ try {clienteSocket.close();}catch (IOException e){/*Si falla el
cierre del socket*/}}

}
}

Se le solicita:
• Documentar el código línea a línea indicando que se instruye a la máquina en cada una
de ellas.
• Compilar y ejecutar el proceso servidor en una máquina y el proceso cliente en otra
máquina; logrando obtener el resultado esperado de acuerdo a lo explicado por el docente
en la sesión de clase. Debe presentar, en la siguiente sesión, la ejecución lograda a su
profesor de la asignatura y contestar a las preguntas que éste le haga sobre el proceso
seguido por usted(es) para lograr el resultado.
• La frase a utilizar para que el servidor responda repitiéndola será: Esta frase va desde el
cliente al servidor y regresa, es un servidor ECO.

2. Enumere dos diferencias importantes entre los dos protocolos presentados.

PARTE 3. Comunicación entre procesos en la misma máquina

Se entrega a usted(es) el código fuente para implementar un proceso muy sencillo que usa un “socket”
servidor instanciable y procesos cliente (hilados) que pueden conectarse a dicho proceso servidor. Compile,
ejecute, documente línea a línea y efectúe el análisis correspondiente de lo que sucede.

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

class hiloCliente extends Thread {

DataInputStream dis = null;


Socket s = null;

public hiloCliente()
{
try {
s = new Socket("127.0.0.1", 2525);
dis = new DataInputStream(s.getInputStream());
}
catch (IOException e)
{
System.out.println("Error: " + e);
}
}

public void run()


{
while (true)
{
try {
String mensaje = dis.readLine();
System.out.println(mensaje + " yo soy el proceso cliente");
if (mensaje == null)
break;

System.out.println(mensaje);
}
catch (IOException e)
{
System.out.println("Error: " + e);
}
}
}
}

public class pruebaClienteYServidor extends Frame {


static ServerSocket servidor = null;

public boolean handleEvent (Event evt)


{
if (evt.id == Event.WINDOW_DESTROY)
{
System.exit(0);
}
return super.handleEvent (evt);
}

public boolean mouseDown(Event evt, int x, int y)


{
new hiloCliente().start();
return(true);
}

public static void main(String args[])


{
pruebaClienteYServidor f = new pruebaClienteYServidor();
f.resize (200, 200);

f.show();

try {
servidor = new ServerSocket(2525);
}
catch (IOException e)
{
System.out.println("Error: " + e);
}

while (true)
{
Socket s = null;

try {
s = servidor.accept();
}
catch (IOException e)
{
System.out.println("Error: " + e);
}

try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("ESTA ES UNA CONEXION ENTRE PROCESOS SOBRE LA MISMA MAQUINA USANDO SOCKETS");
ps.flush();
s.close();
}
catch (IOException e)
{
System.out.println("Error: " + e);
}
}
}
}
PARTE 4. Comunicación entre procesos en diferentes máquinas

Usted(es) deben tomar el código fuente de la PARTE 3 y adaptarlo para que el cliente y el servidor se
ejecuten en dos máquinas diferentes en una red. Compile, ejecute, documente el código línea a línea y
efectúe el análisis correspondiente sobre los cambios efectuados.

PARTE 5. Multidifusión

Comunicación hacia un grupo de procesos se puede hacer con sockets, averigue:

1. ¿Qué protocolo es el utilizado para comunicación entre procesos usando multidifusión?


2. ¿Qué aplicaciones son las más comunes usando multidifusión?

Revise y ejecute el código siguiente, analice los resultados:

package Multidifusion;
import java.net.*;
import java.io.*;
public class participanteMultidifusion {
public static void main(String args[]){
//Use una dirección multidifusión válida, ejemplo: 224.0.0.7
MulticastSocket s =null;
try {
InetAddress grupo = InetAddress.getByName(args[1]);
s = new MulticastSocket(6700);
s.joinGroup(grupo);
byte [] m = args[0].getBytes();
DatagramPacket mensaje = new DatagramPacket(m, m.length,
grupo, 6700);
s.send(mensaje);
byte[] buffer = new byte[1000];
for(int i=0; i< 3;i++) {
DatagramPacket mensajeEntrada = new
DatagramPacket(buffer, buffer.length);
s.receive(mensajeEntrada);
System.out.println("Recibido el mensaje al grupo:" + new
String(mensajeEntrada.getData()));
}
s.leaveGroup(grupo);
}catch (SocketException e){System.out.println("Socket: " +
e.getMessage());
}catch (IOException e){System.out.println("IO: " + e.getMessage());
}finally {if(s != null) s.close();}
}

You might also like