服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

rmi调用模版

1. 定义远程接口 

// 远程接口继承自remote

// 远程方法的传入参数和返回值必须是自然类型(int,float,boolean等)

// 或者实现了serializable或remote接口的对象。

public interface time extends java.rmi.remote {

    // 远程方法必须抛出remoteexception:

    public string gettime() throws remoteexception;

}

 

2. 定义实现类 

// 注意:实现类继承自unicastremoteobject和自定义的远程接口time:

public class timeimpl extends java.rmi.server.unicastremoteobject implements time {

    // 注意:由于remoteobject构造函数要抛出remoteexception,

    // 因此务必定义构造函数并抛出remoteexception:

    public timeimpl() throws remoteexception { super(); }

 

    // 这里是远程方法:

    public string gettime() throws remoteexception {

        return "12:04:27";

    }

 

    // 启动服务:

    public static void main(string[] args) throws exception {

        // 可以手动启动rmi registry,也可以在程序中启动:

        java.rmi.registry.locateregistry.createregistry(1099);

        // 绑定名字服务,地址是本地计算机名或本机ip,默认端口是1099:

        java.rmi.naming.bind("//localhost:1099/servicename", new timeimpl());

        // 如果没有异常抛出,则绑定成功。

        // 如果名字已经被绑定,可以用naming.rebind()替换掉已绑定的服务。

    }

}

 

3. 编译生成桩和框架 

运行rmic timeimpl,生成timeimpl_skel.classtimeimpl_stub.class

 

4. 客户端

// 客户端文件包含客户端代码client.class,远程接口time.class

// 由rmic生成的支持类timeimpl_skel.classtimeimpl_stub.class

public static void main(string[] args) throws exception {

    // 客户端通过ip引用服务器端的远程对象,因此可以动态选择服务器。

    // 如果不指定端口,默认端口号是1099:

    time time = (time)java.rmi.naming.lookup("//localhost:1099/servicename");

    system.out.println(time.gettime());

}

扫描关注微信公众号