サンプル
サーバとクライアント間のインターフェース
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.server.UnicastRemoteObject; public class HelloWorld extends UnicastRemoteObject implements IHelloWorld { private static final long serialVersionUID = 1L; protected HelloWorld() throws RemoteException { super(); } @Override public String sayHello(String name) throws RemoteException { return "Hello World, " + name + "!"; } }
サーバ側
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class HelloWorldServer { public static void main(String[] args) { try { Registry registry = LocateRegistry.createRegistry(1199); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { registry.unbind("HelloWorld"); } catch (Exception ex) { ex.printStackTrace(); } } })); HelloWorld helloWorld = new HelloWorld(); registry.bind("HelloWorld", helloWorld); System.out.println("Server ready"); } catch (Exception ex) { System.err.println("Server exception:" + ex.toString()); ex.printStackTrace(); } } }
クライアント側
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(1199); IHelloWorld stub; try { System.currentTimeMillis(); stub = (IHelloWorld) registry.lookup("HelloWorld"); String response = stub.sayHello("Smith"); 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(); } } }
実行結果
(1) サーバ側を実行させるServer ready(2) クライアント側を実行させる
response:Hello World, Smith!
参考文献
http://blogs.wankuma.com/kazuki/archive/2007/09/23/97632.aspxhttp://d.hatena.ne.jp/kei4eva4/20100914/1284540083
http://qiita.com/Fushihara/items/65113c58c6091784f0a1