EclipseでJavaRMIのHello world!
ここの内容をEclipseで。
http://java.sun.com/javase/ja/6/docs/ja/technotes/guides/rmi/hello/hello-world.html
- リモートインタフェースの定義
File > New > Interface からNameを"Hello"、packageを"example.hello"、Extended interfacesのAddから"java.rmi.Remote"を選択してFinish。
コードを以下のように書き換える。
package example.hello; import java.rmi.Remote; import java.rmi.RemoteException; public interface Hello extends Remote { String sayHello() throws RemoteException; }
- サーバーの実装
File > New > Class からNameを"Server"、packageを"example.hello"、Extended interfacesのAddから"example.hello.Hello"を選択してFinish。
コードを以下のように書き換える。
package example.hello; 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( ); } } }
- クライアントの実装
File > New > Class からNameを"Client"、packageを"example.hello"にしてFinish。
コードを以下のように書き換える。
package example.hello; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Client { public static void main(String[] args) { String host = (args.length < 1) ? null : args[0]; Registry registry; try { registry = LocateRegistry.getRegistry(host); Hello stub; try { System.currentTimeMillis(); stub = (Hello) registry.lookup("Hello"); String response = stub.sayHello(); System.out.println("response:" + response); } catch (NotBoundException e) { System.err.println("Client exception:" + e.toString()); e.printStackTrace(); } } catch (RemoteException e) { System.err.println("Client exception:" + e.toString()); e.printStackTrace(); } } }
これでサンプルプログラムは完成。
実行の手順。
Terminalをたちあげ、"rmiregistry"を実行する。
- サーバーの起動
Run > Run Configurationsから、Serverクラスを実行する。この時、利用できるサーバ側のクラスの場所(codebase)を設定する。ArgumentsのVM Argumentsに"-Djava.rmi.server.codebase=file:${workspace_loc}/プロジェクト名/bin/"に指定する。
Server ready
- クライアントの実行
ClientクラスをRun。
response:Hello, world!