RMI example in Java 2 Platform SE 5.0
RMI stands for Remote Method Invocation. As of the J2SE 5.0 release, stub classes for remote objects no longer need to be pregenerated using the rmic
stub compiler, unless the remote object needs to support clients running in pre-5.0 VMs. So because I'm testing RMI with the JDK 5.0, I won't compile stub classes.
First define interface:
public interface Hello extends java.rmi.Remote { String sayHello() throws java.rmi.RemoteException; }
Server class:
import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class Server implements Hello { public Server() {} public String sayHello() { return "Hello, world!"; } public static void main(String args[]) { System.setSecurityManager(new RMISecurityManager()); final Server obj = new Server(); try { // 0 - anonymous TCP port ↓ Hello stub = (Hello)UnicastRemoteObject.exportObject(obj, 0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.createRegistry(1099); registry.rebind("Hello", stub); for(int i = 0; i < registry.list().length; i++) System.out.println(registry.list()[i]); System.err.println("Server ready"); } catch (Exception e) { e.printStackTrace(); } // Needed for windows98 se, optional for windows xp new Thread() { public void run() { Server s = obj; while(true); } }.start(); } }
Client class:
import java.rmi.registry.*; import java.rmi.*; 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"); // or Hello stub = (Hello)Naming.lookup("rmi://" + host + "/Hello"); String response = stub.sayHello(); System.out.println("response: " + response); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } } }
Create file policy.txt
with this text inside:
grant { // Allow everything for now permission java.security.AllPermission; };
On the server computer run:
java -Djava.security.policy=policy.txt Server
On the client computer run:
java Client 192.168.0.3
Note: substitute ip address of your own or write hostname instead of ip address.
Feel free to post your questions or comments.
1 Comments:
Thanks for the example...it's working in the way it was suppose to ...
Post a Comment
<< Home