JAVA RMI添加示例

时间:2018-11-21 13:46:11

标签: java rmi

我正在实现一个简单的Java RMI应用程序。它的主要目的是添加2个整数。代码源如下: 客户端和服务器端的AdditionInterface import java.rmi.*; public interface AdditionInterface extends Remote { public int add(int a,int b) throws RemoteException; }

Addition.java

 import java.rmi.*;
 import java.rmi.server.*;

 public class Addition extends UnicastRemoteObject
 implements AdditionInterface {

 public Addition () throws RemoteException { }

 public int add(int a, int b) throws RemoteException {
 int result=a+b;
 return result;
 }
 }

AdditionServer

import java.rmi.*;
 import java.rmi.server.*;

 public class AdditionServer {
 public static void main (String[] argv) {
 try {
 System.setSecurityManager(new SecurityManager());

 Addition Hello = new Addition();
 Naming.rebind("rmi://localhost/ABC", Hello);

 System.out.println("Addition Server is ready.");
 }catch (Exception e) {
 System.out.println("Addition Server failed: " + e);
 }
 }
}

AdditionClient

import java.rmi.*;

 public class AdditionClient {
 public static void main (String[] args) {
 AdditionInterface hello;
 try {
 System.setSecurityManager(new SecurityManager());
 hello = (AdditionInterface)Naming.lookup("rmi://localhost/ABC");
 int result=hello.add(9,10);
 System.out.println("Result is :"+result);

 }catch (Exception e) {
 System.out.println("HelloClient exception: " + e);
 }
 }
 }

客户端和服务器端的安全策略

    grant {
        permission java.security.AllPermission;

  };

但是我得到了HelloClient异常:java.security.AccessControlException:访问被拒绝(“ java.net.SocketPermission”“ 127.0.0.1:1099”“ connect,resolve”)  错误

1 个答案:

答案 0 :(得分:-1)

您必须先启动RMI注册表。尝试致电

java.rmi.registry.LocateRegistry.createRegistry(1099);

在尝试(重新)绑定您的远程对象之前。我不确定,但是如果注册表已经启动,则此调用可能会失败。 您的第二个问题可能是SecurityManager应用的策略没有连接/解析本地主机的权限。尝试向System.setSecurityManager(new SecurityManager());注释掉以开始使用。默认的Java策略文件仅授予一个SocketPermission:

permission java.net.SocketPermission "localhost:0", "listen";