サンプル
サーバとクライアント間のインターフェース
import java.rmi.Remote; import java.rmi.RemoteException; public interface IHelloWorld extends Remote { String sayHello(String name) throws RemoteException; }
サーバ側
import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class HelloWorldServer implements IHelloWorld { public static void main(String[] args) { try { System.setProperty("java.rmi.server.hostname", "localhost"); HelloWorldServer server = new HelloWorldServer(); IHelloWorld stub = (IHelloWorld) UnicastRemoteObject.exportObject(server, 28080); Registry registry = LocateRegistry.getRegistry(); registry.rebind("HelloWorld", stub); System.out.println("Server ready"); } catch (Exception ex) { System.err.println("Server exception:" + ex.toString()); ex.printStackTrace(); } } @Override public String sayHello(String name) throws RemoteException { return "Hello World, " + name + "!"; } }
クライアント側
import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class HelloWorldClient { public static void main(String[] args) { Registry registry; try { registry = LocateRegistry.getRegistry(""); IHelloWorld stub; try { System.currentTimeMillis(); stub = (IHelloWorld) registry.lookup("HelloWorld"); String response = stub.sayHello("Mike"); System.out.println("response:" + response); } catch (NotBoundException ex) { System.err.println("Client exception:" + ex.toString()); ex.printStackTrace(); } } catch (RemoteException ex) { System.err.println("Client exception:" + ex.toString()); ex.printStackTrace(); } } }
参考文献
http://d.hatena.ne.jp/kei4eva4/20100914/1284540083http://qiita.com/Fushihara/items/65113c58c6091784f0a1