Java RMI 之牛刀小試

按照wiki說明的例子,照貓畫虎實現java rmi 。以下是擼主的具體步驟:

1、聲明遠程調用的接口,並且自定義接口要繼承java.rmi.remote:

public interface RmiServerIntf extends Remote {

	public String getMessage() throws RemoteException;
}
2、遠程接口的實現類以及遠程服務開啓的main主方法:

public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4312093539786965438L;

	private static String MESSAGE = "Hello, RMI!";
	/**
	 * @throws RemoteException
	 */
	protected RmiServer() throws RemoteException {
		super(0); // required to avoid the 'rmic' step, see below
	}

	/* (non-Javadoc)
	 */
	public String getMessage() throws RemoteException {
		return MESSAGE;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println("RMI Server started");
		try {
			LocateRegistry.createRegistry(1099);
			System.out.println("java RMI registry created.");
		} catch (RemoteException e) {
			//do nothing, error means registry already exists
            System.out.println("java RMI registry already exists.");
		}
		//Instantiate RmiServer
        RmiServer obj = new RmiServer();
     // Bind this object instance to the name "RmiServer"
        Naming.rebind("//localhost/RmiServer", obj);
        System.out.println("PeerServer bound in registry");
	}

}
3、新建調用遠程方法的客戶端類:

public class RmiClient {

	public static void main(String[] args) throws Exception {
		RmiServerIntf server = (RmiServerIntf) Naming.lookup("//localhost/RmiServer");
		System.out.println(server.getMessage());
	}
}
OK, 有了遠程服務類,開啓服務的主函數,還有個調用遠程方法的客戶端類,接下來的步驟:

1、運行RmiServer的main方法, 控制檯顯示如下,則正確:



2、然後保持遠程服務開啓,運行RmiClient類,如果成功調用,那麼已經入門rmi。

note that:

1、遠程服務的端口默認是1099,所以你調用的時候可以省略端口,直接localhost/<your_service_name>;

2、註冊的服務的ip 和 port 與客戶端調用的ip port 一定要一致.


發佈了77 篇原創文章 · 獲贊 2 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章