题目如下:
开发一个称为“城市信息”服务器的应用程序,这个城市信息服务器的客户程序通过提供一个城市名,获得这个城市的相关信息。在此应用程序中,服务器程序只提供两个方法:一个获取人口;另一个获取温度。
而且必须用RMI去实现。
(1)定义一个远程接口MyRmi
文件名:MyRmi.java
- import java.rmi.*;
- public interface MyRmi extends Remote {
- public int sum(String a) throws RemoteException;
- public int tem(String b) throws RemoteException;
- }
(2)实现远程接口和服务器;
文件名:RmiImpl.java
- import java.rmi.*;
- import java.rmi.server.*;
- public class RmiImpl extends UnicastRemoteObject
- implements MyRmi {
- RmiImpl() throws RemoteException {
- super();
- }
- public int sum(String a) throws RemoteException {
- int s=0;
- if(a.equals("保定"))
- s=1000000;
- if(a.equals("北京"))
- s=2000000;
- if(a.equals("石家庄"))
- s=1500000;
- return s;
- }
- public int tem(String b) throws RemoteException {
- int s=0;
- if(b.equals("保定"))
- s=26;
- if(b.equals("北京"))
- s=28;
- if(b.equals("石家庄"))
- s=29;
- return s;
- }
- }
文件名:RmiServer.java
- import java.rmi.*;
- import java.rmi.registry.*;
- public class RmiServer{
- public static void main(String args[]) {
- try {
- LocateRegistry.createRegistry(8808) ;
- RmiImpl Server = new RmiImpl();
- // 将该对象实例与名称“SAMPLE-SERVER”捆绑
- Naming.rebind("//localhost:8808/SAMPLE-SERVER" , Server);
- } catch (java.net.MalformedURLException me) {
- System.out.println("Malformed URL: " + me.toString());
- } catch (RemoteException re) {
- System.out.println("Remote exception: " + re.toString());
- }
- }
- }
(3)使用远程接口开发一个客户程序;
文件名:RmiClient.java
- import java.rmi.*;
- import java.rmi.server.*;
- public class RmiClient {
- public static void main(String[] args)
- {
- try {
- String url = "//localhost:8808/SAMPLE-SERVER";
- MyRmi RmiObject = (MyRmi)Naming.lookup(url);
- System.out.println(" 北京市人口是 " + RmiObject.sum("北京") );
- System.out.println(" 北京市温度是 " + RmiObject.tem("北京") );
- } catch (RemoteException exc) {
- System.out.println("Error in lookup: " + exc.toString());
- } catch (java.net.MalformedURLException exc) {
- System.out.println("Malformed URL: " + exc.toString());
- } catch (java.rmi.NotBoundException exc) {
- System.out.println("NotBound: " + exc.toString());
- }
- }
- }
(4)产生桩和构架。
编写一个批处理文件Build.bat,方便操作。写入下面内容.
javac MyRmi.java RmiImpl.java RmiServer.java RmiClient.java
rmic -v1.2 Rmilmpl
其中rmic -v1.2 Rmilmpl会在目录下产生RmiImpl_Stub.class
(5)启动RMI注册表。
rmiregistry
这条命令用于启动RMI服务器。可以添加到上面的批处理后面。
(6)运行服务器和客户程序。
写两个批处理文件,运行服务端和客户端
java RmiServer
java RmiClient
使用RMI实现远程方法调用
最新推荐文章于 2022-10-09 22:02:31 发布