我的RMI实践
来源:网络 更新时间:2014-12-11
注:本文所涉及代码转自thinkinginJava,但有改动
四个文件:
//:c15:rmi:PerfectTime.java
//From'ThinkinginJava,2nded.'byBruceEckel
//www.BruceEckel.com.SeecopyrightnoticeinCopyRight.txt.
//Theimplementationof
//thePerfectTimeremoteobject.
importjava.rmi.*;
importjava.rmi.server.*;
importjava.rmi.reGIStry.*;
importjava.net.*;
publicclassPerfectTime
extendsUnicastRemoteObject
implementsPerfectTimeI{
//Implementationoftheinterface:
publiclonggetPerfectTime()
throwsRemoteException{
returnSystem.currentTimeMillis();
}
//Mustimplementconstructor
//tothrowRemoteException:
publicPerfectTime()throwsRemoteException{
//super();//Calledautomatically
}
//RegistrationforRMIserving.Throw
//exceptionsouttotheconsole.
publicstaticvoidmain(String[]args)throwsException{
PerfectTimept=newPerfectTime();
Naming.rebind("/PerfectTime",pt);
System.out.println("Readytodotime");
}
}///:~
//:c15:rmi:PerfectTimeI.java
//From'ThinkinginJava,2nded.'byBruceEckel
//www.BruceEckel.com.SeecopyrightnoticeinCopyRight.txt.
//ThePerfectTimeremoteinterface.
importjava.rmi.*;
interfacePerfectTimeIextendsRemote{
longgetPerfectTime()throwsRemoteException;
}///:~
//:c15:rmi:DisplayPerfectTime.java
//From'ThinkinginJava,2nded.'byBruceEckel
//www.BruceEckel.com.SeecopyrightnoticeinCopyRight.txt.
//UsesremoteobjectPerfectTime.
importjava.rmi.*;
importjava.rmi.registry.*;
publicclassDisplayPerfectTime{
publicstaticvoidmain(String[]args)
throwsException{
System.setSecurityManager(
newRMISecurityManager());
PerfectTimeIt=(PerfectTimeI)Naming.lookup("/PerfectTime");
for(inti=0;i<10;i )
System.out.println("Perfecttime="
t.getPerfectTime());
}
}///:~
grant{
//Alloweverythingfornow
permissionjava.security.AllPermission;
};
存入于F:\rmi下
操作步骤
F:\rmi>javaPerfectTime
Readytodotime
F:\rmi>javac*.java
F:\rmi>rmicPerfectTime
F:\rmi>startrmiregistry
F:\rmi>javaPerfectTime
Readytodotime
另开一DOS窗口
F:\rmi>java-Djava.security.policy=registerit.policyDisplayPerfectTime
Perfecttime=1011585443953
Perfecttime=1011585443968
Perfecttime=1011585444000
Perfecttime=1011585444000
Perfecttime=1011585444015
Perfecttime=1011585444031
Perfecttime=1011585444031
Perfecttime=1011585444046
Perfecttime=1011585444062
Perfecttime=1011585444062
注意:如果在rmicPerfectTime时报找不到PerfectTime类,请在环境变量中的ClassPath中加入:F:\rmi