What is RMI
Enables the programmer to create distributed applications (Java-Java), in which the methods of
remote Java objects can be invoked from other Java virtual machines, possibly on different hosts.
RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, supporting true object-oriented polymorphism
Architecture
Advantages
- Object Oriented
Mobile Behavior
Design Patterns
Safe and Secure
Easy to Write/Easy to Use
Connects to Existing/Legacy Systems
Write Once, Run Anywhere
How to implement RMI ?
- Write and compile Java code for interfaces
Write and compile Java code for implementation classes
Generate Stub and Skeleton class files from the implementation classes
Write Java code for a remote service host program
Develop Java code for RMI client program
Install and run RMI system
Note: while declaring & implementing methods they should throws RemoteException
How to run a sample program ?
Interface
import java.lang.*;
import java.rmi.*;
public interface Hello extends java.rmi.Remote {
public String sayHellow() throws java.rmi.RemoteException;
}
Implementation Class:
import java.rmi.*;
import java.rmi.server.*;
class HelloImpl extends UnicastRemoteObject implements Hello {
HelloImpl () throws java.rmi.RemoteException { }
public String sayHellow() throws java.rmi.RemoteException
{
System.out.println(“In say Hello ");
return” Hello! Welcome to the world of RMI”;
}
}
Creating the Server
import java.util.*;
import java.rmi.*;
import java.rmi.RMISecurityManager;
public class HelloServer
{
public static void main( String args[] )
{
System.setSecurityManager( new RMISecurityManager());
try {
System.out.println ("Starting Hello Server");
HelloImpl hello =new HelloImpl ();
System.out.println ("Binding Server");
Naming. rebind (“hello", hello );
System. out. print ("Server is waiting");
}
catch( Exception e )
{
System. out. print ("An error occured");
e. printStackTrace ();
System.out.println(e.getMessage());
}
} }
Creating the Client
import java.util.*;
import java.net.*;
import java.rmi.*;
import java.rmi.RMISecurityManager;
public class HelloClient {
public static void main( String args[] ) {
System.setSecurityManager( new RMISecurityManager());
try {
System.out.println("Starting calcClient");
String url = new String( “rmi://"+ args[0] + "/hello");
System.out.println(“Hello Server Lookup: url =" + url);
hello = (Hello)Naming.lookup( url );
if(hello != null )
{ System.out.println(hello.sayHello());//invoking remote method
} else {
System.out.println("Requested Remote object is null.");
}
} catch( Exception e ) {
System.out.println("An error occurred");
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Start the rmi registry
start rmiregistry
Compile all classes
Create stubs & skeletons
rmic HelloImpl
Start the server
java HelloServer
Start the Client
java HelloClient localhost
Sample program architecture
No comments:
Post a Comment