天天看點

Java中RMI遠端調用

  java rmi極大地依賴于接口。在需要建立一個遠端對象的時候,程式員通過傳遞一個接口來隐藏底層的實作細節。用戶端得到的遠端對象句柄正好與本地的根代碼連接配接,由後者負責透過網絡通信。這樣一來,程式員隻需關心如何通過自己的接口句柄發送消息。

  服務端建立接口:

import java.rmi.remote;

import java.rmi.remoteexception;

public interface rmitestinterface extends remote{

public string gettest() throws 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

  定義一個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);

 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) {

  運作用戶端main方法後,控制台輸出:

  hello,test

english »

afrikaansalbanianarabicarmenianazerbaijanibasquebengalibelarusianbulgariancatalanchinese (simp)chinese (trad)croatianczechdanishdutchenglishesperantoestonianfilipinofinnishfrenchgaliciangeorgiangermangreekgujaratihaitian creolehebrewhindihungarianicelandicindonesianirishitalianjapanesekannadakoreanlaolatinlatvianlithuanianmacedonianmalaymaltesenorwegianpersianpolishportugueseromanianrussianserbianslovakslovenianspanishswahiliswedishtamilteluguthaiturkishukrainianurduvietnamesewelshyiddish

<a target="_blank"></a>

最新内容請見作者的github頁:http://qaseven.github.io/