Java Reference
In-Depth Information
rMI in Java
try it out
This exercise will help you see how Java RMI works. You will create a simple server for two basic num-
ber manipulations: addition and subtraction.
1.
Create two classes and an interface: RMIClient , RMIServer , and RMIInterface . Create a package
called rmiexample to hold them.
2.
Start with RMIInterface . This interface defines the methods the server will expose to the client
without specifying the actual code to be executed, just as a normal interface would. The code for
RMIInterface looks like this:
package rmiexample;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RMIInterface extends Remote {
public int addTwoNumbers(int a, int b) throws RemoteException;
public int substractTwoNumbers(int a, int b) throws RemoteException;
}
3.
The RMIServer class implements this interface and thus specifies the method body for addTwoNum-
bers and substractTwoNumbers . A main method is also included in this class and it instantiates
an RMIServer object:
package rmiexample;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
public class RMIServer
extends UnicastRemoteObject implements RMIInterface {
public RMIServer() throws RemoteException {
super();
}
public int addTwoNumbers(int a, int b) throws RemoteException {
System.out.println("addTwoNumbers was called");
return a + b;
}
public int substractTwoNumbers(int a, int b) throws RemoteException {
System.out.println("substractTwoNumbers was called");
return a - b;
}
public static void main(String args[]) throws Exception {
System.out.println("Starting server...");
Search WWH ::




Custom Search