下面我将介绍一个完整的实例,让初学者能快速体验RMI的功用。
分为以下四个步骤
1. 创建远程接口及声明远程方法(HelloInterface.java)
2. 实现远程接口及远程方法(继承UnicastRemoteObject)(Hello.java)
3. 启动RMI注册服务,并注册远程对象(HelloServer.java)
4. 客户端查找远程对象,并调用远程方法(HelloClient)
5. 执行程序:启动服务HelloServer;运行客户端HelloClient进行调用
具体代码及对应步骤如下:
1. 创建远程接口及声明远程方法(HelloInterface.java)
java 代码
packagecn.telling.rmi;importjava.rmi.Remote;importjava.rmi.RemoteException;/*** 远程接口必须扩展接口java.rmi.Remote
*
* @ClassName: HelloInterface TODO
*@authorxingle
* @date 2015-9-28 下午4:37:12*/
public interface HelloInterface extendsRemote ,Serializable{/*** 远程接口方法必须抛出 java.rmi.RemoteException*/
public String sayHello() throwsRemoteException;;
}
2. 实现远程接口及远程方法(继承UnicastRemoteObject)HelloImpl.java
java 代码
packagecn.telling.rmi;importjava.rmi.RemoteException;importjava.rmi.server.UnicastRemoteObject;/*** 扩展了UnicastRemoteObject类,并实现远程接口 HelloInterface
*
* @ClassName: HelloImpl TODO
*@authorxingle
* @date 2015-9-28 下午4:38:47*/
public class HelloImpl extends UnicastRemoteObject implementsHelloInterface {privateString message;/*** 必须定义构造方法,即使是默认构造方法,也必须把它明确地写出来,因为它必须抛出出RemoteException异常
*
*@parammsg
*@throwsRemoteException*/
public HelloImpl(String msg) throwsRemoteException {this.message =msg;
}/***
* @Description: TODO
*@return*@throwsRemoteException
*@authorxingle
* @data 2015-9-28 下午4:39:41*/@Overridepublic String sayHello() throwsRemoteException {
System.out.println("Called by HelloClient");returnmessage;
}
}
3. 启动RMI注册服务,并注册远程对象(HelloServer.java)
java 代码
packagecn.telling.rmi;importjava.net.MalformedURLException;importjava.rmi.Naming;importjava.rmi.RemoteException;importjava.rmi.registry.LocateRegistry;/***
* @ClassName: HelloServer TODO
*@authorxingle
* @date 2015-9-28 下午4:41:47*/
public classHelloServer {public static voidmain(String[] args) {try{//启动RMI注册服务,指定端口为1099 (1099为默认端口)//也可以通过命令 $java_home/bin/rmiregistry 1099启动//这里用这种方式避免了再打开一个DOS窗口//而且用命令rmiregistry启动注册服务还必须事先用RMIC生成一个stub类为它所用
LocateRegistry.createRegistry(1099);//创建远程对象的一个或多个实例//可以用不同名字注册不同的实例
HelloImpl service = new HelloImpl("hello,world!");//如果要把hello实例注册到另一台启动了RMI注册服务的机器上//Naming.rebind("//192.168.1.105:1099/Hello",hello);
Naming.rebind("Hello", service);
System.out.println("Hello Server is ready.");
}catch(RemoteException e) {
System.out.println("Hello Server failed: " +e);
e.printStackTrace();
}catch(MalformedURLException e) {
e.printStackTrace();
}
}
}
4. 客户端查找远程对象,并调用远程方法(HelloClient)
java 代码
packagecn.telling.rmi;importjava.rmi.Naming;/***
* @ClassName: HelloClient TODO
*@authorxingle
* @date 2015-9-28 下午4:54:51*/
public classHelloClient {public static voidmain(String[] argv) {try{
HelloInterface hello= (HelloInterface) Naming.lookup("Hello");//如果要从另一台启动了RMI注册服务的机器上查找hello实例//HelloInterface hello =//(HelloInterface)Naming.lookup("//192.168.1.105:1099/Hello");//调用远程方法
System.out.println(hello.sayHello());
}catch(Exception e) {
System.out.println("HelloClient exception: " +e);
}
}
}
5. 执行程序:启动服务HelloServer;运行客户端HelloClient进行调用
执行结果:
服务端:
客户端:
参考:
《Head First 设计模式》