Remote communication between applications using RMI (Remote Method Invocation) in Java - Tutorial18/5/2018
Remote Method Invocation is a Java API that allows for objects to invoke methods from another object running in the same or different JVM. It is used to create distributed applications in Java.
To be a distributed application, an application needs to be able to:
RMI allows applications to become distributed by achieving the above. RMI uses stubs and skeletons to communicate with remote objects. A stub, is an object used for client-side communication whereas the skeleton is is used for server-side communication. Let's see how to create distributed applications using RMI. Disclaimer: I do not own any content. The following code is an amalgamation of different codes available on numerous websites that include: StackOverflow, TutorialsPoint, etc. Prerequisite: The only knowledge required is a thorough knowledge of Java. Installations: None, except Java (obviously). Procedure: In this tutorial I will show you the implementation of RMI by requesting a function from the server that returns the value of Pi (π) accurate upto 12 digits. In order to create a distributed application we need to create the following files:
import java.rmi.*; public interface MathConstants extends Remote { public double pi() throws RemoteException; }
import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class MathConstantsImpl extends UnicastRemoteObject implements MathConstants { MathConstantsImpl() throws RemoteException { super(); } public double pi() { return 3.141592653589; } }
import java.rmi.Naming; public class Client { public static void main(String args[]){ try{ int port = 7100; String lookup_url="rmi://localhost:"+port+"/Constants"; MathConstants con = (MathConstants)Naming.lookup(lookup_url); System.out.println("Area of a circle with radius 3 is: "+ (con.pi()*3*3)); }catch(Exception e){ System.out.println("Error: "+e); } } }
import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Server { public static void main(String args[]) throws RemoteException{ try{ int port = 7100; startRegistry(port); MathConstantsImpl con = new MathConstantsImpl(); String url = "rmi://localhost:"+port+"/Constants"; Naming.rebind(url,con); System.out.println("Server ready."); }catch(Exception e){ System.out.println("Error: "+e); } } private static void startRegistry(int port) throws RemoteException { try{ Registry registry = LocateRegistry.getRegistry(port); registry.list(); System.out.println("Found Registry"); }catch(Exception e){ System.out.println("Registry not found. Creating Registry...."); LocateRegistry.createRegistry(port); System.out.println("New Registry Created"); } } }
Try this out yourself in the meantime and let me know about any errors or doubts you may have in the comments section below.
0 Comments
|
Archives
December 2018
Categories
|