【Java】Java間でのデータの受け渡し ~ RMI (Remote Method Invocation) ~

サンプル

サーバとクライアント間のインターフェース

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!


関連記事

Socket 通信を行う ~Server側/Client側の実装例~

https://blogs.yahoo.co.jp/dk521123/33075148.html

簡単なチャットツールを作成する

https://blogs.yahoo.co.jp/dk521123/35113609.html

SocketChannel / ServerSocketChannel ~ブロッキングモード編~

http://blogs.yahoo.co.jp/dk521123/35067257.html

SocketChannel / ServerSocketChannel ~ノンブロッキングモード編~

http://blogs.yahoo.co.jp/dk521123/35120798.html