Steps
Server
- Make a remote interface
- Extend java.rmi.Remote
- Declare that all methods throw a RemoteException
- arguments and return value should be Serializable or primitives
ITestRemoteService.java
import java.rmi.*;
public interface ITestRemoteService extends Remote {
public String helloWorld() throws RemoteException;
}
- Make a remote implementation
- Implement the remote interface
- Extend UnicastRemoteObject
- write no argument constructor that declares a RemoteException
- Register the service with the RMI registry
TestRemoteService.java
import java.rmi.*;
import java.rmi.server.*; // import for UnicastRemoteObject usage
public class TestRemoteService extends UnicastRemoteObject implements ITestRemoteService {
public static void main(String[] args) {
try{
TestRemoteService myTestService = new TestRemoteService();
Naming.rebind("TestRemoteService", myTestService); //bind to rmiregistry
} catch(Exception ex) {
ex.printStackTrace();
}
}
public TestRemoteService() throws RemoteException {} //UnicastRemoteObject declares an exception
public String helloWorld() {
return "Hello, George!";
}
}
- Generate the stubs and skeletons (this is deprecated for new java versions) using rmic
- Split out the two new classes for the helper objects
- NOTE: In Java 5, RMI and Dynamic Proxy got toghether and now stubs are generated dynamically using Dynamic Proxy. The remote objcet's stub is a java.lang.reflect.Proxy instance (with an invocation handler).
>javac -d class ITestRemoteService.java
>javac -d class TestRemoteService.java
>cd class
>rmic TestRemoteService
- Start the RMI registry (rmiregistry)
>rmiregistry
- Start the remote service
>java TestRemoteService
Client
- Have a client class (in a client folder)
- Copy interface and stubs to the client folder
- Client does a lookup on the RMI registry
- RMI registry returns the stub object
- stub class should be on the client (also the interface class)
- Client invokes a method on the stub
TestRemoteClient.java
import java.rmi.*;
public class TestRemoteClient {
public static void main(String[] args) {
try {
ITestRemoteService service = (ITestRemoteService) Naming.lookup("rmi://127.0.0.1/TestRemoteService");
String str = service.helloWorld();
System.out.println(str);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
>javac -d class TestRemoteClient.java
>cd class
>java TestRemoteClient
Hello, George!