In this tutorial how to perform RMI (Remote Method Invocation) in Advance Java (J2EE) is shown.
RMI system allows an object running in one Java Virtual Machine (JVM) to invoke methods of an object running in another JVM.
Code:
Prime.java
import java.rmi.*;
public interface Prime extends Remote
{
public int check_prime(int no) throws RemoteException;
}
Prime_Impli.java
import java.rmi.*;
import java.rmi.server.*;
public class Prime_Impli extends UnicastRemoteObject implements Prime
{
public Prime_Impli() throws Exception{}
public int check_prime(int no) throws RemoteException
{
int i,cnt=0;
for(i=2;i<=no/2;i++)
{
if(no%i==0)
{
cnt++;
break;
}
}
return(cnt);
}
}
Prime_server.java
import java.rmi.*;
import java.net.*;
public class Prime_server
{
public static void main(String args[])
{
try
{
Prime_Impli primpli=new Prime_Impli();
Naming.rebind(“RmiPrime”,primpli);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Prime_client.java
import java.io.*;
import java.rmi.*;
import java.net.*;
public class Prime_client
{
public static void main(String args[])
{
try
{
String url=”rmi://localhost/RmiPrime”;
Prime intf=(Prime)Naming.lookup(url);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter a no:”);
int no=Integer.parseInt(br.readLine());
int x=intf.check_prime(no);
if(x==0)
System.out.println(no+” is a prime number”);
else
System.out.println(no+” is a composite number”);
}
catch(Exception e)
{
System.out.println(e);
}
}
}