Programación en Java: Comunicación entre procesos con Sockets TCP, UDP y RMI

Informática8,82 KB

Comunicación entre procesos con Sockets TCP y UDP

Comunicación mediante UDP y TCP

Los siguientes ejemplos muestran una cadena de comunicación entre tres procesos (E1, E2 y E3), combinando sockets TCP y sockets UDP.

public class E1 { public static void main(String[] args) throws IOException { // Comunicación con E2 (TCP) Socket socketE2 = new Socket(InetAddress.getLocalHost(), 5000); DataOutputStream salidaE2 = new DataOutputStream(socketE2.getOutputStream()); // Solicitar 5 números positivos al usuario Scanner scanner = new Scanner(System.in); int count = 0; while (count < 5) { System.out.print("Introduce un número positivo: "); int numero = scanner.nextInt(); if (numero > 0) { salidaE2.writeInt(numero); count++; } else { System.out.println("Número inválido. Intenta de nuevo."); } } salidaE2.close(); socketE2.close(); // Comunicación con E3 (UDP) DatagramSocket socketE3 = new DatagramSocket(4445); byte[] buffer = new byte[128]; while (true) { DatagramPacket paquete = new DatagramPacket(buffer, buffer.length); socketE3.receive(paquete); String mensaje = new String(paquete.getData()).trim(); int numero = Integer.parseInt(mensaje); if (numero == -10) break; // Fin de la comunicación System.out.println("Número recibido de E3: " + numero); } socketE3.close(); } }

public class E2 { public static void main(String[] args) throws IOException { // Comunicación con E1 (TCP) ServerSocket serverE1 = new ServerSocket(5000); Socket socketE1 = serverE1.accept(); DataInputStream entradaE1 = new DataInputStream(socketE1.getInputStream()); // Recibir 5 números de E1 int[] numeros = new int[5]; for (int i = 0; i < 5; i++) { numeros[i] = entradaE1.readInt(); } entradaE1.close(); socketE1.close(); serverE1.close(); // Duplicar los números int[] duplicados = new int[10]; for (int i = 0; i < 5; i++) { duplicados[i * 2] = numeros[i] * 2; duplicados[i * 2 + 1] = numeros[i] / 2; } // Comunicación con E3 (TCP) Socket socketE3 = new Socket(InetAddress.getLocalHost(), 5001); DataOutputStream salidaE3 = new DataOutputStream(socketE3.getOutputStream()); for (int numero : duplicados) { salidaE3.writeInt(numero); } salidaE3.close(); socketE3.close(); } }

public class E3 { public static void main(String[] args) throws IOException { // Comunicación con E2 (TCP) ServerSocket serverE2 = new ServerSocket(5001); Socket socketE2 = serverE2.accept(); DataInputStream entradaE2 = new DataInputStream(socketE2.getInputStream()); // Recibir 10 números de E2 int[] numeros = new int[10]; for (int i = 0; i < 10; i++) { numeros[i] = entradaE2.readInt(); } entradaE2.close(); socketE2.close(); serverE2.close(); // Filtrar números (eliminar múltiplos de 3) DatagramSocket socketE1 = new DatagramSocket(); InetAddress destino = InetAddress.getLocalHost(); for (int numero : numeros) { if (numero % 3 != 0) { byte[] buffer = String.valueOf(numero).getBytes(); DatagramPacket paquete = new DatagramPacket(buffer, buffer.length, destino, 4445); socketE1.send(paquete); } } // Enviar -10 para indicar el fin de la comunicación byte[] buffer = String.valueOf(-10).getBytes(); DatagramPacket paquete = new DatagramPacket(buffer, buffer.length, destino, 4445); socketE1.send(paquete); socketE1.close(); } }


Java RMI: cálculo de edad

Interfaz remota y su implementación

public interface CalculaEdad extends Remote { int dias(int a) throws RemoteException; int meses(int b) throws RemoteException; int año(int c) throws RemoteException; int dias(int a, int b) throws RemoteException; }

public class CalculaEdadImp extends UnicastRemoteObject implements CalculaEdad { public CalculaEdadImp() throws RemoteException { super(); } @Override public int dias(int a) throws RemoteException { return 13 - a; } public int meses(int b) throws RemoteException { return 5 - b; } @Override public int año(int c) throws RemoteException { return 2025 - c; } @Override public int dias(int a, int b) throws RemoteException { return 0; } }

Cliente y servidor RMI

public class Cliente { public static void main(String[] args) { try { CalculaEdad obj = (CalculaEdad) Naming.lookup("//localhost/CalculaEdad"); Scanner sc = new Scanner(System.in); System.out.print("Introduce día de nacimiento: "); int a = sc.nextInt(); // Espera a que introduzca el número a System.out.print("Introduce mes: "); int b = sc.nextInt(); System.out.print("Introduce año: "); int c = sc.nextInt(); int diasr = obj.dias(a); int mesesr = obj.meses(b); int añosr = obj.año(c); System.out.println("Días: " + diasr); System.out.println("Meses: " + mesesr); System.out.println("Año: " + añosr); } catch (Exception e) { System.err.println("Excepción en cliente: " + e.getMessage()); e.printStackTrace(); } } }

public class Servidor { public static void main(String[] args) { try { CalculaEdad obj = new CalculaEdadImp(); // Crear registro RMI en el puerto 1099 Registry registry = LocateRegistry.createRegistry(1099); // Registrar el objeto remoto con nombre Naming.rebind("//localhost/CalculaEdad", obj); System.out.println("Servidor RMI de CalculaEdad listo."); } catch (Exception e) { System.err.println("Error en el servidor: " + e.getMessage()); e.printStackTrace(); } } }


Cálculo de edad con UDP

Cliente UDP

public class ClienteUDP { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(); InetAddress destino = InetAddress.getByName("localhost"); // Enviar fecha de nacimiento String fechaNacimiento = "2001-06-15"; // Cámbiala si deseas byte[] buf = fechaNacimiento.getBytes(); DatagramPacket paquete = new DatagramPacket(buf, buf.length, destino, 4445); socket.send(paquete); // Recibir respuesta (edad) buf = new byte[128]; paquete = new DatagramPacket(buf, buf.length); socket.receive(paquete); String respuesta = new String(paquete.getData()).trim(); System.out.println("Edad calculada: " + respuesta); socket.close(); } }

Servidor UDP

public class ServidorUDP { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(4445); try { byte[] buf = new byte[128]; DatagramPacket paquete = new DatagramPacket(buf, buf.length); socket.receive(paquete); // Espera el datagrama String fechaRecibida = new String(paquete.getData()).trim(); System.out.println("Fecha recibida: " + fechaRecibida); // Calcular edad LocalDate nacimiento = LocalDate.parse(fechaRecibida); LocalDate hoy = LocalDate.now(); int edad = Period.between(nacimiento, hoy).getYears(); String mensaje = String.valueOf(edad); // Preparar respuesta buf = mensaje.getBytes(); InetAddress destino = paquete.getAddress(); int puerto = paquete.getPort(); paquete = new DatagramPacket(buf, buf.length, destino, puerto); socket.send(paquete); // Enviar la respuesta } catch (IOException e) { e.printStackTrace(); } finally { socket.close(); } } }


Cálculo de edad con TCP

Cliente TCP

public class Cliente { public static void main(String args[]) { Socket cliente; DataInputStream entrada; DataOutputStream salida; try { cliente = new Socket(InetAddress.getLocalHost(), 49152); // Creamos el socket para conectarnos al puerto 49152 entrada = new DataInputStream(cliente.getInputStream()); // Creamos los canales de E/S salida = new DataOutputStream(cliente.getOutputStream()); // Enviar la fecha de nacimiento String fechaNacimiento = "2005-06-15"; salida.writeUTF(fechaNacimiento); // Recibir la edad calculada String respuesta = entrada.readUTF(); System.out.println("Edad calculada: " + respuesta); entrada.close(); // Cerramos los flujos de entrada y salida salida.close(); cliente.close(); // Cerramos la conexión } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } } }

Servidor TCP

public class Servidor { public static void main(String args[]) { ServerSocket servidor; Socket conexion; DataOutputStream salida; DataInputStream entrada; int num = 0; try { servidor = new ServerSocket(49152); // Creamos un ServerSocket en el puerto 49152 System.out.println("Servidor arrancado..."); while (true) { conexion = servidor.accept(); // Esperamos una conexión num++; System.out.println("Conexión n." + num + " desde: " + conexion.getInetAddress().getHostName()); entrada = new DataInputStream(conexion.getInputStream()); // Abrimos los canales de E/S salida = new DataOutputStream(conexion.getOutputStream()); String mensaje = entrada.readUTF(); // Leemos el mensaje del cliente System.out.println("Conexión n." + num + " mensaje: " + mensaje); // Calcular edad LocalDate fechaNacimiento = LocalDate.parse(mensaje); LocalDate hoy = LocalDate.now(); int edad = Period.between(fechaNacimiento, hoy).getYears(); // Enviar la edad al cliente salida.writeUTF(String.valueOf(edad)); entrada.close(); // Cerramos los flujos de entrada y salida salida.close(); conexion.close(); // Y cerramos la conexión } // No alcanzable } catch (IOException e) { } } }

Descargar

PDF Word HTML