這段時間碰巧做一個RMI的應用,剛上手還是用舊的方法完成,不曾想過JDK在RMI有了較大的簡化。是以在此通過一個小的demo,把這部分知識點與大家分享。非常感謝夢夢同學讓我對這部分内容得以重新鞏固。
JDK5下的RMI示例編寫與操作步驟如下。
1、建立接口
public interface SecureSecond extends Remote
{
long getMilliSeconds() throws RemoteException;
}
2、建立實作類
public class SecureSecondImpl extends UnicastRemoteObject implements
SecureSecond {
private static final long serialVersionUID = 1L;
public SecureSecondImpl() throws RemoteException {
};
public long getMilliSeconds() throws RemoteException {
// The method getTime returns the time in msecs
System.out.println("method called");
long time = new Date().getTime();
System.out.println("job done");
return time;
};
}
3、建立服務端
public class SecureServer {
public static void main(String[] args) {
try {
System.out.println("Loading in security manager");
RMISecurityManager sManager = new RMISecurityManager();
System.setSecurityManager(sManager);
SecureSecondImpl remote = new SecureSecondImpl();
Naming.rebind ("Dater", remote);
System.out.println("Object bound to name");
}
catch(Exception e) {
System.out.println("Error occurred at server "+e.getMessage());
}
}
}
4、建立用戶端
public class SecureTimeClient {
public static void main(String[] args) {
try {
System.out.println("Loading in security manager");
RMISecurityManager sManager = new RMISecurityManager();
System.setSecurityManager(sManager);
SecureSecond sgen = (SecureSecond) Naming.lookup("rmi://localhost/Dater");
System.out.println("Milliseconds are "+sgen.getMilliSeconds());
}
catch(Exception e) {
System.out.println("Problem encountered accessing remote object "+e);
}
}
}
5、編譯以上檔案
6、注冊RMI
在“運作”中輸入cmd,在你的class目錄下執行 start rmiregistry
7、修改權限,
打開你安裝java的目錄,找到
Java\jdk1.6.0_06\jre\lib\security\java.policy檔案,用記事本打開
在grant { }所轄的括号中加一句:
permission java.security.AllPermission "", "";
8、啟動服務端
在“運作”中輸入cmd,在你的class目錄下執行
java -Djava.security.policy=java.policy SecureServer
9、在“運作”中輸入cmd,在你的class目錄下執行
java -Djava.security.policy=java.policy SecureTimeClient