【zz】RMI的基本使用
使用步骤
1.建立server包:用于保存RMI的服务类
2.建立interfaces包:用于保存所有的抽象接口
3.建立impls包:用于保存服务器端抽象接口的具体实现类
4.建立client包:保存客户端相关类
注意事项:
1.作为RMI的抽象接口必须throws RemoteException
2.RMI抽象接口的实现类必须要有公用的构造方法、实现类必须extends UnicastRemoteObject,并且构造方法必须throws RemoteException
复制内容到剪贴板
代码:
public class RemoteServerImp extends UnicastRemoteObject implements
OperatorRmiInterface {
public RemoteServerImp() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
//.......................
//服务类
try {
LocateRegistry.createRegistry(8888); //服务器端注册服务端口
RemoteServerImp simp = new RemoteServerImp();//实例化一个服务类
Naming.rebind("//localhost:8888/SIMPLE-SERVER", simp);//将服务类和URL绑定到命名空间
System.out.println("RMI Server Started");
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//客户端
String url = "//localhost:8888/SIMPLE-SERVER";
try {
OperatorRmiInterface in = (OperatorRmiInterface)Naming.lookup(url);//在命名空间上查找服务URL
System.out.println("call remote program 1+2="+in.sum(1, 2));//调用远程服务端的方法
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
唐山迪锐软件:www.tsp2c.cn