Remote Method Invocation What is a RMI? Before JDK1.1, the networked applications were sockets-based programming. With RMI, Java objects can easily invoke the methods of remote objects as if they were locally available. The compute engine server accepts tasks from clients, runs the tasks, and returns any results. The server is comprised of an interface and a class. The interface provides the definition for the methods that can be called from the client. Essentially the interface defines the client's view of the remote object. The class provides the implementation. How does it work? Define the remote interfaces (include all functions that can be called remotely): package examples.hello; import java.rmi.Remote; import java.rmi.RemoteException; public interface Hello extends Remote { String sayHello() throws RemoteException; } Provide the implementation for the remote interface. package examples.hello; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.RMISecurityManager; import java.rmi.server.UnicastRemoteObject; public class HelloImpl extends UnicastRemoteObject implements Hello{ public HelloImpl() throws RemoteException { super(); //default and can be omitted } public String sayHello () { return "Hello World!"; } public static void main (String args []) { // Create and install a security manager, try { HelloImpl obj = new HelloImpl() ; // Bind this object instance to the name "HelloServer" Client program (Clients program to remote interfaces, not to the implementation classes of those interfaces.) package examples.hello; public class HelloApplet extends Applet { public void init() { try { obj = (Hello)Naming.lookup("//" + getCodeBase().getHost() + "/HelloServer"); message = obj.sayHello(); } catch (Exception e) { System.out.println("HelloApplet exception:"+e.getMessage()); e.printStackTrace(); } } public void paint(Graphics g) { g.drawString(message, 25, 50); } } The client may begin by installing a security manager. This is necessary because RMI could be downloading code to the client. The client constructs a name used to look up a remote object. To generate a stub for the remote object so that clients can contact the remote object. Before starting the compute engine, you need to start RMI's registry, using the rmiregistry command. Web Sites
|