Ⅰ. はじめに
タイトルの通り「JavaRMI で HelloWorld する方法」です。
Ⅱ. やり方
1. サンプルプログラムを書く
com/company/client/Client.java
package com.company.client; import com.company.core.Common; import com.company.core.IHello; 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) throws RemoteException, NotBoundException { Registry reg = LocateRegistry.getRegistry(Common.RMI_HOST, Common.RMI_PORT); IHello hello = (IHello) reg.lookup(Common.RMI_NAME); System.out.println(hello.helloWorld("tanaka")); } }
com/company/core/Common.java
package com.company.core; public class Common { public static final String RMI_NAME = "MyServer"; public static final String RMI_HOST = "10.226.0.1"; public static final int RMI_PORT = 1099; }
com/company/core/IHello.java
package com.company.core; import java.rmi.Remote; import java.rmi.RemoteException; public interface IHello extends Remote { String helloWorld(String name) throws RemoteException; }
com/company/server/Hello.java
package com.company.server; import com.company.core.IHello; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Hello extends UnicastRemoteObject implements IHello { protected Hello() throws RemoteException { super(); } @Override public String helloWorld(String name) throws RemoteException { return "hello world " + name; } }
com/company/server/Server.java
package com.company.server; import com.company.core.Common; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class Server{ public static void main(String[] args) throws RemoteException, AlreadyBoundException { Registry registry = LocateRegistry.createRegistry(Common.RMI_PORT); registry.bind(Common.RMI_NAME, new Hello()); System.out.println("server started"); } }
2. コンパイルする
javac^ -d out^ src/com/company/client/Client.java^ src/com/company/core/Common.java^ src/com/company/core/IHello.java^ src/com/company/server/Hello.java^ src/com/company/server/Server.java
3. サーバを起動する
java -classpath out com.company.server.Server
4. クライアントを起動する
java -classpath out com.company.client.Client
実行結果
hello world tanaka