Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

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

$
0
0

サンプル

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

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.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class HelloWorldServer implements IHelloWorld {

  public static void main(String[] args) {
    try {
      System.setProperty("java.rmi.server.hostname", "localhost");

      HelloWorldServer server = new HelloWorldServer();
      IHelloWorld stub = (IHelloWorld) UnicastRemoteObject.exportObject(server, 28080);

      Registry registry = LocateRegistry.getRegistry();
      registry.rebind("HelloWorld", stub);

      System.out.println("Server ready");
    } catch (Exception ex) {
      System.err.println("Server exception:" + ex.toString());
      ex.printStackTrace();
    }
  }

  @Override
  public String sayHello(String name) throws RemoteException {
    return "Hello World, " + name + "!";
  }
}

クライアント側

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("");
      IHelloWorld stub;
      try {
        System.currentTimeMillis();
        stub = (IHelloWorld) registry.lookup("HelloWorld");
        String response = stub.sayHello("Mike");
        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();
    }
  }
}


関連記事

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

Viewing all articles
Browse latest Browse all 860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>