JAVA远程方法-RMI

来源:互联网 发布:信息群发软件通科 编辑:程序博客网 时间:2024/05/02 19:41

    Java1.1的“远程方法调用”(RMI)用抽象的概念实现了一台机器调用另外一台机器的方法。简单记录实现方法,以便今后查阅。

    RMI对接口有着强烈的依赖。在需要创建一个远程对象的时候,我们通过传递一个接口来隐藏基层的实施细节,所以客户端得到的远程对象的一个句柄时,它们真正得到的是接口的句柄。这个接口正好同一些本地的根代码连接。简单来说就是通过接口调用远程的代码。接口必须遵守下列规则:

(1)、远程接口必须为public属性。

(2)、远程接口必须拓展接口java.rmi.Remote。

(3)、除与应用程序本身有关的违例之外,远程接口中的每个方法都必须在自己的throws从句中声明java.rmi.RemoteException。

(4)、作为参数或返回值传递的一个远程对象,必须声明为远程接口,不可声明为实施类。

简单例子:

一、远程接口

interface PerfectTimeI extends Remote {long getPerfectTime() throws RemoteException;}
二、接口实施

public class PerfectTime extends UnicastRemoteObject implements PerfectTimeI {// Implementation of the interface:public long getPerfectTime() throws RemoteException {return System.currentTimeMillis();}// 必须有构造函数,并抛出RemoteException异常public PerfectTime() throws RemoteException {// super(); // Called automatically}// Registration for RMI serving:public static void main(String[] args) {try {PerfectTime pt = new PerfectTime();//注册通讯端口              LocateRegistry.createRegistry(2015);            Naming.bind("rmi://172.16.0.55:2015/PerfectTime", pt);System.out.println("Ready to do time");} catch (Exception e) {e.printStackTrace();}}} // /:~
三、使用远程对象

可将上面的PerfectTimeI接口打包,放到别的项目中,然后使用该接口调用代码。

public class DisplayPerfectTime {public static void main(String[] args) {try {PerfectTimeI t = (PerfectTimeI) Naming.lookup("rmi://172.16.0.55:2015/PerfectTime");for (int i = 0; i < 10; i++)System.out.println("Perfect time = " + t.getPerfectTime());} catch (Exception e) {e.printStackTrace();}}} // /:~




    

0 0
原创粉丝点击