在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值