Java中RMI远程调用

Kaitlyn ·
更新时间:2024-09-21
· 890 次阅读

  Java远程方法调用,即Java RMI(Java Remote Method Invocation)是Java编程语言里,一种用于实现远程过程调用的应用程序编程接口。它使客户机上运行的程序可以调用远程服务器上的对象。远程方法调用特性使Java编程人员能够在网络环境中分布操作。RMI全部的宗旨是尽可能简化远程接口对象的使用。   Java RMI极大地依赖于接口。在需要创建一个远程对象的时候,程序员通过传递一个接口来隐藏底层的实现细节。客户端得到的远程对象句柄正好与本地的根代码连接,由后者负责透过网络通信。这样一来,程序员只需关心如何通过自己的接口句柄发送消息。   服务端新建接口:

 

import java.rmi.Remote; import java.rmi.RemoteException; public interface RmiTestInterface extends Remote{ public String getTest() throws RemoteException; }

  接口的实现:

 

import java.rmi.RemoteException; public class RmiTestImpl implements RmiTestInterface { public RmiTestImpl() throws RemoteException { //super(); // TODO Auto-generated constructor stub //UnicastRemoteObject.exportObject(this); } /** * */ public String getTest() throws RemoteException { // TODO Auto-generated method stub return "Hello,Test"; } }

  定义一个main方法,注册你已经实现的RMI接口,包括开放端口等:

 

public static void main(String []args) throws AlreadyBoundException, RemoteException{ RmiTestImpl t=new RmiTestImpl(); RmiTestInterface tt=(RmiTestInterface)UnicastRemoteObject.exportObject(t,0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.createRegistry(2001); registry.rebind("test", tt); System.out.println("server is start"); }

  Server端的代码已经全部写完,但是还要把接口类(RmiTestInterface)打包成jar,导入进client端的项目中。   运行服务端后控制台输出:   server is start   导入服务端的接口jar以后,可以开始编写一个client端的主程序:

public static void main(String []args){ try { Registry registry = LocateRegistry.getRegistry("localhost",2001); RmiTestInterface t= (RmiTestInterface) registry.lookup("test"); System.out.println("client:"+t.getTest()); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
  运行客户端main方法后,控制台输出:   Hello,Test



rmi JAVA 调用

需要 登录 后方可回复, 如果你还没有账号请 注册新账号