トップ 差分 一覧 ソース 置換 検索 ヘルプ PDF RSS ログイン

JavaでRMI

1.Remote を継承したインターフェイスを作成
2.作成したインターフェイスを実装したクラスを作成し、処理を書く
3.サーバは2のインスタンスを登録
4.クライアントはサーバに登録されているオブジェクトを1のインターフェイスでアクセス

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;

// class RemoteObject extends UnicastRemoteObject implements Remote {
// class RemoteInterface extends UnicastRemoteObject implements Remote {
interface RemoteInterface  extends Remote {
  public String test(String a, String b) throws RemoteException;
}

// class RemoteObject extends RemoteInterface {
class RemoteObject extends UnicastRemoteObject implements RemoteInterface {
  public RemoteObject() throws RemoteException {
    super();
  }
  
  public String test(String a, String b){
    return a + b;
  }
}

public class RMIServer {
  public static void main(String[] args){
    try{
      Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);

      RemoteObject ro = new RemoteObject();
      Naming.rebind("RMIServer", ro);//リモートオブジェクトに名前をつける
      // Naming.rebind("//localhost/RMIServer", ro);//リモートオブジェクトに名前をつける
      System.out.println("RMIServer bound in registry");
    } catch(Exception e){
      e.printStackTrace();
    }
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.rmi.*;

public class RMIClient {
  public static void main(String[] args){
    String remotehost = "localhost";
    // if (args.length < 1){
      // System.out.println("Usage: java RMIClient [remotehost]");
      // System.exit(1);
    // }
    
    if(args.length == 1){
      remotehost = args[0];
    }
    
    try{
      RemoteInterface ro = 
      (RemoteInterface)Naming.lookup(";//"+remotehost+"/RMIServer");
      
      System.out.println(ro.test("hoge","test"));
      
      System.out.println(Naming.lookup(";//"+remotehost+"/RMIServer").getClass());
      
    } catch(Exception e){
      e.printStackTrace();
    }
  }
}
[カテゴリ: プログラミング言語 > Java]

[通知用URL]



  • Hatenaブックマークに追加
  • livedoorクリップに追加
  • del.icio.usに追加
  • FC2ブックマークに追加

最終更新時間:2010年11月13日 01時04分27秒