Sample RMI Implementation In Java:

Implementing Remote Interface:
A remote object is an instance of a class that implements a remote interface. A remote interface extends the interface java.rmi.Remote and declares a set ofremote methods. Each remote method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions.
//hellointerface.java
import java.rmi.*;
public interface hellointerface extends Remote
{
public String say()throws RemoteException;
}
Implementing Remote Class
//hello.java
import java.rmi.*;
import java.rmi.server.*;
public class hello extends UnicastRemoteObject implements hellointerface
{
private String message;
public hello(String msg)throws RemoteException
{
message=msg;
}
public String say()throws RemoteException
{
return message;
}
}
Implementing Server
A "server" class, in this context, is the class which has a main method that creates an instance of the remote object implementation, exports the remote object, and then binds that instance to a name in a Java RMI registry. The class that contains this main method could be the implementation class itself, or another class entirely.
//server.java
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
class server
{
public static void main (String[] argv)
{
try {
hello obj=new hello ("Hello, world!");
Naming.rebind ("hello",obj );
System.out.println ("Hello Server is ready.");
} catch (Exception e) {
System.out.println ("Hello Server failed: " + e);
}
}
}
Implementing Client
The client program obtains a stub for the registry on the server's host, looks up the remote object's stub by name in the registry, and then invokes the sayHello method on the remote object using the stub.
//client.java
import java.io.*;
import java.rmi.*;
class client
{
public static void main(String arg[])throws Exception
{
hellointerface obj=(hellointerface)Naming.lookup("hello");
System.out.println(obj.say());
}
}
How To Run???
step1: Create class file by compiling all the java files created above.
step2: Create stub using stub compiler."stub hello".
step3: Start the registry."rmiregistry &".
step4: Run the server."java server".
step5: Run the client."java client".

Comments

Unknown said…
i want RMi program with database . can u help me? j2eekme@yahoo.in forward to my mail id

Popular Posts