远程方法调用
基本原理:
java开发人员想通过网络访问其他其他机器上的代码,传统的方法实现很容易出错。rmi的基本原理是:将想要执行的代码一个类(服务类)的形式放在其他机器上,当访问时,通过网络向此服务类发送消息,并接受结果,就与在本机上调用发法相同。
实现流程:
1.拓展java.rmi.Remote借口,完成服务类的借口。
注: 每个方法必须抛出java.rmi.RemoteException。
2.实现拓展后的借口。
注:此类必须继承java.rmi.UnicastRemote类,此类完成了与RMI系统的相关连结。
并且,此类必须有显示的构造方法。
3.使用rmic工具生成xxx_stub.class“根”和xxx_skel.class“干”。
注:此两类负责底层通信,分别负责分发和处理类。
4.注册远程类。
5.调用远程服务类。
实例源码:
1./*
*Create on Dec 31, 2008
*Copyright 2009 Quasar20063501.All Rights reserved
*
*weizhaozhe
*/
package wzz.service;
import java.rmi.*;
import java.rmi.RemoteException;
public interface RmtService extends Remote{
public void Test()throws RemoteException;
}
2
/*
*Create on Dec 31, 2008
*Copyright 2009 Quasar20063501.All Rights reserved
*
*weizhaozhe
*/
package wzz.service;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class RmtServiceImpl extends UnicastRemoteObject implements RmtService{
public RmtServiceImpl() throws RemoteException{
super();
}
public void Test() throws RemoteException {
System.out.println("Hello World!");
}
}
3命令行输入:rmic wzz.service.RmtServiceImpl
注:可先在命令行中输入rmic回车,得到有关rmic命令的有关参数,根据实际情况取舍。
4.
/*
*Create on Dec 31, 2008
*Copyright 2009 Quasar20063501.All Rights reserved
*
*weizhaozhe
*/
package wzz.server;
import java.rmi.*;
import wzz.service.*;
public class Server {
public static void main(String args[]){
try{
RmtServiceImpl service=new RmtServiceImpl();
String registration="rmi://localhost:8888/RmtService";
Naming.rebind(registration, service);
}catch(RemoteException re){
System.out.println("There is a RemoteException happened!/n");
System.out.println("Details:"+re);
}catch(Exception e){
System.out.println("There is a Exception happened!/n");
}
}
}
5
/*
*Create on Dec 31, 2008
*Copyright 2009 Quasar20063501.All Rights reserved
*
*weizhaozhe
*/
package wzz.client;
import wzz.service.*;
import java.rmi.*;
public class Client {
public static void main(String args[]){
try{
String registration="rmi://localhost:8888/RmtService";
RmtService rmtServ=(RmtService)Naming.lookup(registration);
rmtServ.Test();
}catch(RemoteException re){
System.out.println("There is a RemoteException happened!/n");
System.out.println("Details:"+re);
}catch(Exception e){
System.out.println("There is a Exception happened!/n");
}
}
}
这就完成了,功能的实现就靠你们了,哈哈