Java远程方法调用,即Java RMI(Java Remote Method Invocation)是Java编程语言里,一种用于实现远程过程调用的应用程序编程接口。它使客户机上运行的程序可以调用远程服务器上的对象。远程方法调用特性使Java编程人员能够在网络环境中分布操作。RMI全部的宗旨就是尽可能简化远程接口对象的使用。
我们先写一个接口和服务端接口的实现,顺便写了一个可序列化的类,验证对象的可以远程调用和传递:
// 接口
package com.server;
import java.rmi.Remote;
import java.rmi.RemoteException;
import com.server.bean.Hello;
public interface HelloRemote extends Remote{
public String sayHello() throws RemoteException;
public Hello getHello() throws RemoteException;
}
//接口实现
package com.server;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import com.server.bean.Hello;
public class HelloRemoteImpl extends UnicastRemoteObject implements HelloRemote{
protected HelloRemoteImpl() throws RemoteException { }
@Override
public String sayHello() throws RemoteException {
return " say hello!";
}
@Override
public Hello getHello() throws RemoteException {
Hello eric = new Hello();
eric.setName("Eric");
return eric;
}
}
// 可序列化类
package com.server.bean;
import java.io.Serializable;
public class Hello implements Serializable{
String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
下面实现一个启动服务器的入口,rmiregistry不需要手动启动,而且stub和skeleton类也不需要手动生成了。其中stub类是客户端需要的代理类,由服务器端产生,在客户端调用方法时动态下载到客户端,客户端通过stub类来和服务器的skeleton类交互,skeleton类是服务器端的代理类,接收到客户端的调用时,匹配服务器端对应的方法,然后执行并返回结果到客户端。
//服务器端入口:
package com.server;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Test {
public static void main(String[] args) {
try {
HelloRemoteImpl helloRemoteImpl = new HelloRemoteImpl();
Registry registry = LocateRegistry.createRegistry(7777);
registry.rebind("hello", helloRemoteImpl);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
为了让客户端能够知道服务器端有什么接口和相关的类可以使用,我们把服务器端的接口和可序列化的类打包成jar库,在创建客户端工程时导入这个类库,这样我们就知道可以调用那些远程方法了。
//客户端
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import com.server.HelloRemote;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 7777);
HelloRemote helloRemote = (HelloRemote)registry.lookup("hello");
System.out.println(helloRemote.getHello().getName()+helloRemote.sayHello());
} catch (Exception e) {
e.printStackTrace();
}
}
}
先运行服务器端的Test类,然后运行客户端,就可以看到执行结果。