`
xmh517
  • 浏览: 64306 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

在JDK5中,RMI的简单运用

阅读更多

      这段时间碰巧做一个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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics