rmi的服務端,必須要使用接口,同時還有接口的實作類!是以下面的兩個檔案是接口類和接口的實作類!
userdao 接口:
/**
* 遠端接口 必須繼承與remote對象
* @author spring sky
* date: 2012年2月7日 10:55:05
* email:[email protected]
* qq:840950105
*/
public interface userdao extends remote{
/**
* @param name
*/
public void sayname(string name) throws remoteexception;
}
userdaoimpl實作類
*
* 接口的實作類 必須繼承unicastremoteobject(單一遠端對象) 實作userdao自己的接口
* date: 2012年2月7日 10:56:05
public class userdaoimpl extends unicastremoteobject implements userdao {
public userdaoimpl() throws remoteexception {
}
@override
public void sayname(string name) {
if(name!=null&&!name.equals(""))
{
system.out.println("我的名字是:"+name);
}else{
system.err.println("名字不為空....");
}
對外的提供一個服務,服務中已經共享了url給外界通路
* 使用main方法啟動一個服務,用于外界環境通路
* date:2012年2月7日 10:57:37
public class startservice {
private static final string ip = "127.0.0.1";
private static final int port = 9999;
private static final string remote_name = "userdao";
private static final string remote_url = "rmi://"+ip+":"+port+"/"+remote_name;
public static void main(string[] args) {
try {
userdao userdao = new userdaoimpl(); //執行個體化對象
locateregistry.createregistry(port); //注冊端口
naming.bind(remote_url, userdao); //綁定遠端服務對象
system.out.println("遠端"+remote_name+"啟動成功....");
} catch (remoteexception e) {
system.err.println("遠端對象出錯");
e.printstacktrace();
} catch (malformedurlexception e) {
system.err.println("url出錯了");
} catch (alreadyboundexception e) {
system.err.println("綁定的對象已經存在了");
上面是服務端的代碼,如果啟動沒有任何問題,就可以做用戶端通路了,其實用戶端的通路更加的簡單,隻需要遠端的接口類和查詢rmi中的url就可以了!
代碼如下:
/**
* 遠端方法調用測試
* @author spring sky
* date:2012年2月7日 11:12:46
* email:[email protected]
* qq:840950105
* name:石明政
public class testremote {
//在rmi服務中查詢userdao的對象
userdao userdao = (userdao) naming.lookup("rmi://127.0.0.1:9999/userdao");
//調用遠端服務的方法
userdao.sayname("spring sky");
system.err.println("url出錯");
} catch (notboundexception e) {
system.err.println("沒有找到綁定的對象");
以上就是所有的rmi遠端調用代碼了!運作結果如下:
好了,本人也隻是簡單的了解了rmi,如果以後有項目做rmi就可以深入了! 呵呵 ,在這裡我突然感覺,想web service也應該和他一樣的原理的把!
本文出自seven的測試人生公衆号最新内容請見作者的github頁:http://qaseven.github.io/