---
title: "RMI调用模版"
author: "mmdev"
date: "2004-07-04T14:02:00Z"
tags: []
slug: "rmi"
draft: false
lastmod: "2004-07-04T14:02:00Z"
id: 1006748
url: "https://mmdev.iteye.com/blog/1006748"
---

**1. 定义远程接口**

// 远程接口继承自Remote&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt;

// 远程方法的传入参数和返回值必须是自然类型（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** "&lt;?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /&gt;&lt;time w:st="on" minute="4" hour="12"&gt;12:04:27&lt;/time&gt;";

}

// 启动服务：

**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.class*和*TimeImpl\_Stub.class*。

**4. 客户端**

// 客户端文件包含客户端代码*Client.class*，远程接口*Time.class*，

// 由*rmic*生成的支持类*TimeImpl\_Skel.class*和*TimeImpl\_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());

}