Code for RMI application for counting factorial of a given number. in Java
// FactRMI.java Interfacepublicinterface FactRMI extends java.rmi.Remote
{
long countfact(int num) throws java.rmi.RemoteException;
}
// FactRMIImpl.java, FactRMI implementation
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
publicclass FactRMIImpl extends UnicastRemoteObject implements FactRMI
{
privateint fact;
public FactRMIImpl(String name) throws RemoteException
{
super();
try
{
Naming.rebind(name, this);
fact = 1;
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
publiclong countfact(int num) throws RemoteException
{
for(int i=1;i<=num;i++)
{
fact = fact * i;
}
return fact;
}
}
// FactRMIServer.java
import java.rmi.*;
import java.rmi.server.*;
publicclass FactRMIServer
{
publicstaticvoid main(String args[])
{
// Create and install the security manager
System.setSecurityManager(new RMISecurityManager());
try
{
// Create CountRMIImpl
FactRMIImpl myFact = new FactRMIImpl("//Binita/myFactRMI");
System.out.println("FactRMI Server ready.");
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
}
}
}
// FactRMIClient.java RMI Count client
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.io.DataInputStream;
publicclass FactRMIClient
{ publicstaticvoid main(String args[])
{
// Create and install the security manager
System.setSecurityManager(new RMISecurityManager());
DataInputStream in = new DataInputStream(System.in);
int num;
try
{
FactRMI myFact = (FactRMI)Naming.lookup("//"
+ args[0] + "/" + "myFactRMI");
System.out.println("\nEnter the number :");
num = Integer.parseInt(in.readLine());
// Calculate Factoriallong FactVal = myFact.countfact(num);
System.out.println("Factorial = " + FactVal);
}
catch(Exception e)
{
System.err.println("System Exception" + e);
}
System.exit(0);
}
}
// OUTPUT
Enter the number :
10
Factorial = 3628800