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/