建立RMI分布式程序简单步骤:
服务器端:
1.
public interface ServiceInterface extends Remote
{
public List getData(String id) throws RemoteException;
public MyData getMyData() throws RemoteException;
}
注意:
第一步是在服务端定义让客户端调用的远程接口.
(1)这些借口一定要声明为公开,可抛出异常.
(2)而且这些借口的返回值和传进的参数都必须是可串行化.
2.
public class ServiceImp extends UnicastRemoteObject implements ServiceInterface
{
public ServiceImp() throws RemoteException
{
super();
}
public List getData(String id) throws RemoteException
{
...
}
public MyData getMyData() throws RemoteException
{
...
}
public void main(String[] args) throws Exception
{
String remoteObjectName = "rmi://localhost/ServiceInterface";
ServiceInterface remoteObject = new ServiceImp();
Naming.rebind(remoteObjectName, remoteObject);
}
}
实现远程接口,并继承UnicastRemoteObject.
注意:
在远程对象ServiceImp的构造函数一定要声明抛出异常和调用父构造函数(super()).
3. 注册远程对象
(1)String remoteObjectName = "rmi://localhost/ServiceInterface";
(2)ServiceInterface remoteObject = new ServiceImp();
(3)Naming.rebind(remoteObjectName, remoteObject);
注意:
这里注册的是远程接口("rmi://localhost/ServiceInterface")只是一个别名,可以去其它名字譬如
("rmi://localhost/A")
关键是(3)那句把这个别名跟remoteOjbect关联起来了.
4. 编译JAVA文件
5. 产生stub and skeleton
rmic -v1.1 ServiceImp
注意:这里会产生两个文件ServiceImp_Stub.class and ServiceImp_Skel.class
6. 启动注册器
start rmiregistry
7. 运行远程对象
java ServiceImp
注意: 这里有可能会出现异常说UnmarshalException, ClassNotFound 什么的. 很有可能是你环境变量的
classpath没设好,因而找不到stub.
客户端:
1. 这里就不用说了
String name = "rmi://localhost/ServiceData";
DataService service = (DataService)Naming.lookup(name);
System.out.println(service.getRemoteData());
![精致生活,声色景象,电影场[url=http://spaces.msn.com/members/sunnywhen/] [/url]](http://node2.foto.ycstatic.com/200505/21/6/22635638.jpg)
![[url=http://sunnywhen.yculblog.com] [/url]晴朗的天空](http://node1.foto.ycstatic.com/200505/12/7/22638935.jpg)

