JAVA RMI例子

时间:2022-09-19 09:01:10

RMI 是java语言的一个RPC框架,本文给出基础例子如下:

1、实现接口:

public interface ICalc extends Remote {
public int add(int param1, int param2) throws java.rmi.RemoteException;
}

2、服务端实现该接口:

public class CalcImpl extends UnicastRemoteObject implements ICalc {

    protected CalcImpl() throws RemoteException {
super();
} @Override
public int add(int param1, int param2) {
return param1 + param2;
} public static void main(String[] args) {
ICalc calc;
try {
//下述代码主要解决connect confused问题
System.setProperty("java.rmi.server.hostname", "192.168.0.16");
calc = new CalcImpl();
LocateRegistry.createRegistry(1011);
java.rmi.Naming.rebind("rmi://192.168.0.16:1011/calc", calc);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

3、定义测试客户端:

public class Client {

    public static void main(String[] args) {
ICalc calc;
try {
calc = (ICalc) Naming.lookup("rmi://192.168.0.16:1011/calc");
System.out.println(calc.add(2,3));
} catch (MalformedURLException | RemoteException | NotBoundException e) {
e.printStackTrace();
}
}
}

4、测试执行顺序:

1、服务器端编译javac CalcImpl

2、生成桩文件rmic CalcImpl,目录下会新增CalcImpl_Stub;

3、执行rmiregister,注册该程序;

4、在新窗口启动服务 java CalcImpl;

5、将CalcImpl_Stub拷贝至客户端,执行java Client;此时客户端打印预算结果