代码改变世界

[原创]Java RMI的简单示例--调用远程方法返回当前时间

2011-05-06 19:58  会被淹死的鱼  阅读(509)  评论(0编辑  收藏  举报

Java RMI是一种与具体网络无关, 轻量级的, 完全可移植的RPC.

这个例子是一个简单的调用, 返回一个当前时间.

RMI远程接口必须实现java.rmi.Remote

import java.util.Date;

public interface RemoteDate extends java.rmi.Remote{
public Date getRemoteDate() throws java.rmi.RemoteException;
public final static String LOOKUPNAME = "RemoteDate";
}

继承了java.rmi.Remote接口, LOOKUPNAME是在RMI中注册和查找用的名字.

RemoteDate接口的实现类

 

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Date;

public class RemoteDateImpl implements RemoteDate, Serializable{

private static final long serialVersionUID = 1L;

@Override
public Date getRemoteDate() throws RemoteException {
return new Date();
}

}

下面写两个类, 一个用于注册RMI, 另一个用来调用RemoteDate

DateClient用来调用远程RemoteDate的方法

 

import java.rmi.Naming;
import java.util.Date;

public class DateClient {
protected static RemoteDate netConn = null;
public static void main(String[] args) {
try {
netConn
= (RemoteDate) Naming.lookup(RemoteDate.LOOKUPNAME);
Date today
= netConn.getRemoteDate();
System.out.println(today.toString());
}
catch (Exception e) {
e.printStackTrace();
}
}
}

DateServer用来注册RemoteDateImpl, 注册名为RemoteDate.LOOKUPNAME

 

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class DateServer {
public static void main(String[] args) {
try {
RemoteDateImpl im
= new RemoteDateImpl();
System.out.println(
"DateServer starting...");
Naming.rebind(RemoteDate.LOOKUPNAME, im);
System.out.println(
"DateServer ready");
}
catch (RemoteException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

其他的准备工作:

在eclipse工程目录的bin目录下, 运行下列命令

>rmic -d . com.icejoywoo.first.RemoteDateImpl

>rmiregistry

(rmic和rmiregistry都是在jdk的bin下, 我这里假设你已经添加了环境变量path)

然后先运行DateServer的main函数

DateServer starting...
DateServer ready

再运行DateClient的main函数

Fri May 06 19:56:16 CST 2011
可以看到, 这个时间是当前的时间