Contenidos
El paquete RMI (Remote Method Invocation) permite manejar objetos (y sus respectivos métodos) de manera remota y transparente para el usuario.
El elemento fundamental es la interfaz remota que sirve para identificar interfaces cuyos métodos pueden invocarse desde una máquina virtual no local.
Cualquier objeto que sea un objeto remoto debe implementar directa o indirectamente esta interfaz. Las clases de implementación pueden implementar cualquier número de interfaces remotas y pueden extender otras clases de implementación remota. RMI proporciona algunas clases de conveniencia que las implementaciones de objetos remotos pueden extender y que facilitan la creación de objetos remotos.
Interfaz remota
Interfaz Java que contiene los métodos que se ejecutarán de forma remota.
1 2 3 4 5 6 |
import java.rmi.Remote; import java.rmi.RemoteException; public interface RMICalcInterface extends Remote { public int suma(int a, int b) throws RemoteException; } |
Servidor
Servidor que implementa la clase de objetos remotos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class RMICalcServer implements RMICalcInterface { public int suma(int a, int b) throws RemoteException { return (a + b); } public static void main(String[] args) { Registry reg = null; try { reg = LocateRegistry.createRegistry(5555); } catch (Exception e) { System.out.println("ERROR: No se ha podido crear el registro"); e.printStackTrace(); } RMICalcServer serverObject = new RMICalcServer(); try { reg.rebind("Calculadora", (RMICalcInterface)UnicastRemoteObject.exportObject(serverObject, 0)); } catch (Exception e) { System.out.println("ERROR: No se ha podido inscribir el objeto servidor."); e.printStackTrace(); } } } |
Cliente
Cliente que utiliza objetos remotos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class RMICalcClient { public static void main(String[] args) { RMICalcInterface calc = null; try { Registry registry = LocateRegistry.getRegistry("localhost", 5555); calc = (RMICalcInterface) registry.lookup("Calculadora"); } catch (Exception e) { e.printStackTrace(); } if (calc != null) { try { System.out.println("2 + 2 = " + calc.suma(2, 2)); } catch (RemoteException e) { e.printStackTrace(); } } } } |