TO execute Java RMI Program, follow below steps.
1. Create a file called “HelloWorldRMIServer.java” as following code.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class HelloWorldRMIServer
{
public static void main(String[] argv)
{
System.setSecurityManager(new RMISecurityManager());
try
{
HelloWorldRMIImpl implementation = new HelloWorldRMIImpl ("HelloWorldRMIImplInstance", "Hello World! from Java RMI Server machine-MITindia");
}
catch (Exception e)
{
System.out.println("Exception occurred: " + e);
}
}
}
2. Next, create a file called “HelloWorldRMIInterface.java” as following code.
import java.rmi.Remote;
public interface HelloWorldRMIInterface extends Remote
{
public String sayHello() throws java.rmi.RemoteException;
}
3. Next, create a file called “HelloWorldRMIImpl.java” as following code in it.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class HelloWorldRMIImpl extends UnicastRemoteObject implements HelloWorldRMIInterface
{
public String message;
public HelloWorldRMIImpl(String name, String msg) throws RemoteException
{
super();
try
{
Naming.rebind(name, this);
message = msg;
}
catch(Exception e)
{
System.out.println("Exception occurred: " + e);
}
}
public String sayHello()
{
return message;
}
}
4. Create another file called “HelloWorldRMIClient.java” as following code.
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class HelloWorldRMIClient
{
public static void main(String[] argv)
{
System.setSecurityManager(new RMISecurityManager());
if (argv.length != 1)
{
System.out.println("usage: java myRMIClient <IP address of host running RMI server>");
System.exit(0);
}
String serverName = argv[0];
try
{
HelloWorldRMIInterface myServerObject = (HelloWorldRMIInterface) Naming.lookup("rmi://"+serverName+"/HelloWorldRMIImplInstance");
String message = myServerObject.sayHello();
System.out.println("Message From Server is " + message);
}
catch(Exception e)
{
System.out.println("Exception occured: " + e);
System.exit(0);
}
System.out.println("RMI connection successful");
}
}
5. Now, Compile all above 4 programs, one by one. [Don’t run now, just compile all!]
6. Create a “permit.policy” file with following syntax in. (use notepad to create this file and save as “permit.policy”)
grant {
permission java.net.SocketPermission "*:1024-65535",
"connect,accept,resolve";
permission java.net.SocketPermission "*:1-1023",
"connect,resolve";
};
7.Go to command prompt and type: start rmiregistry
8. First run server file called “HelloWorldRMIServer” with following style of running.
java -Djava.security.policy=permit.policy HelloWorldRMIServer
9. Next, run client file “HelloWorldRMIClient” as following style of running (in another command prompt and please keep open server command, don’t close it!)
java -Djava.security.policy=permit.policy HelloWorldRMIClient 127.0.0.1
That’s all for running RMI Programs, now keep executing some more RMI programs for practice!
