Java Remote Method Invocation (RMI)
********************************************************************************
Remote Method Invocation (Java RMI).
http://docs.oracle.com/javase/1.5.0/docs/guide/rmi/hello/hello-world.html#4
c:\tmp1\Hello.java
c:\tmp1\Server.java
c:\tmp1\Client.java
Start rmiregistry(default port 1099):
start rmiregistry - the port is 1099
start rmiregistry 2001 - run on port 2001
Compile:
javac -d c:\tmp1\ Hello.java Server.java Client.java
Start Server:
start java -classpath c:\tmp1\ testrmi.Server
Registry registry = LocateRegistry.getRegistry(2001); - if the port is 2001
Start Clinet:
java -classpath c:\tmp1\ testrmi.Client
Registry registry = LocateRegistry.getRegistry(2001); - if the port is 2001
Result:
response: Hello, world!
********************************************************************************
package testrmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}
********************************************************************************
package testrmi;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
********************************************************************************
package testrmi;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
***************************************************************************************************