Java プログラムメモ


トップ

RMI サーバの作り方

Java の RMI テクノロジは非常に簡単にサーバを構築する事が可能であり、Socket を意識する必要もありません。 また、ローカルクラスを使用してるのと変わりなくサーバへのアクセスが可能です。

サーバを起動する為には、JAVA_HOME/jre/lib/security/java.policy に
permission java.security.AllPermission;
を追加しなければいけません。

サーバ側 Interface

import java.rmi.*; public interface RemoteServer extends Remote { public boolean isAlive() throws RemoteException; }

サーバ側 実装クラス

import java.net.*; import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class RemoteServerImpl extends UnicastRemoteObject implements RemoteServer { public RemoteServerImpl(String name, int port) throws RemoteException { System.setSecurityManager(new RMISecurityManager()); LocateRegistry.createRegistry(port); try { Naming.rebind(new StringBuffer(64).append("//:").append(port) .append('/').append(name).toString(), this); } catch (MalformedURLException e) { throw new RemoteException(e.getMessage(), e); } } public boolean isAlive() throws RemoteException { return true; } public static void main(String[] args) { try { new RemoteServerImpl("サービス名", port 番号); } catch (RemoteException e) { e.printStackTrace(); } } }

クライアントクラス

import java.rmi.*; public class RemoteServerClient { public static void main(String[] args) { try { RemoteServer server = (RemoteServer)Naming .lookup("rmi://サーバアドレス:ポート番号/サービス名"); System.out.println(server.isAlive()); } catch (Exception e) { e.printStackTrace(); } } }

プログラムメモ アフリカ雑貨・珈琲豆・アールブリュット作品 マゴソスクール クラウドファンディング
SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送