Java source code for simple addition using RMI

Aim:

To write a java program for Remote Method Invocation.

Algorithm:

 Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a method of a Java object that executes on another machine.

  1. This is an important feature, because it allows you to build distributed applications.
  2. The server receives a request from a client, processes it, and returns a result. In this program, the request specifies two numbers.
  3. The server adds these together and returns the sum.
  4. Create and compile source code.
  5. Run it in client side.

 Source code:

AddServerIntf.java

import java .rmi.*;

public  interface  AddServerIntf  extends  Remote

{double  add(double d1, double d2) throws RemoteException;}

AddServerImpl.java

import java.rmi.*;

import java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObject  implements AddServerIntf

{public AddServerImpl() throws RemoteException

{}

public double add(double d1,double d2) throws RemoteException

{return d1+d2;}}

 

AddServer.java

 

import java .net.*;

import java.rmi.*;

public class AddServer

{

public static void main(String args[])

{

try

{AddServerImpl addServerImpl= new AddServerImpl();

Naming.rebind(“AddServer”, addServerImpl);}

catch(Exception e)

{System.out.println(“Exceptiion: ” +e);}}}

 

 

 

 

AddClient.java

 

import java.rmi.*;

public class AddClient

{

public static void main(String args[])

{

try

{

String addServerURL=”rmi://” + args[0]+”/AddServer”;

AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(addServerURL);

System.out.println(“Thr first number isP: ” +args[1]);

double d1= Double.valueOf(args[1]).doubleValue();

System.out.println(“The second number is :” + args[2]);

double d2= Double.valueOf(args[2]).doubleValue();

System.out.println(“The sum is : ” + addServerIntf.add(d1,d2));

}

catch( Exception e)

{

System.out.println(“Exception : ” +e);

}

}

}

Procedure to run

compile <interface file>

compile <implementation file>

compile <server file>

compile <client file>

rmic <implementation file>

start rmi registry

java <server file>

java<client file>