Java中RMI远程调用demo

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

/*服务端新建接口:*/
public interface RmiTestInterface extends Remote{
public String getTest() throws RemoteException;
}

  

/*接口的实现:*/
public class RmiTestImpl implements RmiTestInterface{
	public RmiTestImpl() throws RemoteException{
		
	}
	@Override
	public String getTest() throws RemoteException{
		
		return "Hello MM";
	}
	public static void main(String[] args) throws RemoteException {
		RmiTestImpl t=new RmiTestImpl();
		RmiTestInterface tt=(RmiTestInterface) UnicastRemoteObject.exportObject(t, 0);
		Registry registry=LocateRegistry.createRegistry(2001);
		registry.rebind("test", tt);
		System.out.println("server is start");
	}

}

  

/*client端的主程序*/
public class 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) {		
		e.printStackTrace();
	}catch (NotBoundException e) {		
		e.printStackTrace();
	}
}
}

  

posted @ 2017-06-16 08:39  ATJAVA  阅读(646)  评论(0编辑  收藏  举报