1. 程式人生 > >Java RMI實現

Java RMI實現

  1. 定義一個遠端介面
public interface IService extends Remote{
    public String queryName(String no) throws RemoteException;
}
  1. 實現遠端的介面
public class ServiceImpl extends UnicastRemoteObject implements IService {


    private static final long serialVersionUID = 1L;

    protected ServiceImpl() throws RemoteException {
    }

    @Override
    public String queryName(String no) throws RemoteException {
        //方法的具體實現
        System.out.println("hello "+ no);
        return String.valueOf(System.currentTimeMillis());
    }
}

  1. RMI伺服器端程式
public class Server {

    public static void main(String[] args) {
        //註冊管理器
        Registry registry = null;
        try {
            //建立一個服務註冊管理器
            registry = LocateRegistry.createRegistry(8088);
            System.out.println("registry");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        try {
            //建立一個服務
            ServiceImpl service = new ServiceImpl();

            //將服務繫結命名
            registry.rebind("vince",service);
            System.out.println("bind server");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  1. RMI客戶端呼叫程式
public class Client {
    public static void main(String[] args) {
        //註冊管理器
        Registry registry = null;
        try {
            //獲取服務註冊管理器
            registry = LocateRegistry.getRegistry("localhost",8088);
            //列出所有註冊的服務
            String[] list = registry.list();
            for (String s : list){
                System.out.println(s);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        try {
            //根據命名獲取服務
            IService service = (IService) registry.lookup("vince");
            //呼叫遠端方法
            String result = service.queryName("jack");
            //輸出呼叫結果
            System.out.println("result from remote : "+result);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (NotBoundException e) {
            e.printStackTrace();
        }

    }
}