1

我最近一直在使用 RMI,虽然我设法让它在 locahost 上工作,但在尝试使用远程服务器时遇到了各种各样的问题。这是我要运行的基本代码:

服务器:

public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {
    public static final String MESSAGE = "Hello world";

    public RmiServer() throws RemoteException {
    }

    public String getMessage() {
    return MESSAGE;
    }

    public static void main(String args[]) {
        System.out.println("RMI server started");

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
            System.out.println("Security manager installed.");
            } else {
                   System.out.println("Security manager already exists.");
            }

            try {
                    LocateRegistry.createRegistry(1099);
                    System.out.println("java RMI registry created.");
            } catch (RemoteException e) {
                    e.printStackTrace();
            }

            try {
                    RmiServer obj = new RmiServer();

                    Naming.rebind("rmi://localhost/RmiServer", obj);

                    System.out.println("PeerServer bound in registry");
            } catch (Exception e) {
                    e.printStackTrace();
            }
      }
}

远程类接口:

public interface RmiServerIntf extends Remote {
    public String getMessage() throws RemoteException;
}

客户:

public class RmiClient { 
    RmiServerIntf obj = null; 

    public String getMessage() { 
        try { 
            obj = (RmiServerIntf)Naming.lookup("rmi://54.229.66.xxx/RmiServer");
            return obj.getMessage(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
            return e.getMessage();
        } 
    } 

    public static void main(String args[]) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        RmiClient cli = new RmiClient();

        System.out.println(cli.getMessage());
    }
}

rmi.policy 文件:

grant {
permission java.security.AllPermission;
};

我编译了这些类并为服务器创建了一个存根。然后我将客户端、存根、接口和策略放在我的机器上,将服务器、存根、接口和策略放在远程机器上。远程服务器是一台 Linux 机器,我使所有文件都可执行。我还在本地防火墙上添加了一条允许端口 1099 的规则,并打开了远程机器上的所有端口

在此之后,我导航到远程机器上的服务器目录并插入以下命令:

java -Djava.security.policy=rmi.policy RmiServer

这没有给我带来问题,所以我回到本地机器并输入

java -Djava.security.policy=rmi.policy RmiClient

我等待,等待,我收到错误消息:

Connection refused to host: 172.31.xx.xx; nested exception is: java.net.ConnectException: Connection timed out: connect 

我昨天整天都在与这些连接错误作斗争,这就是我所得到的。我确信只有一件非常小的事情我仍然做错了,但我就是找不到它是什么。

4

2 回答 2

1

这可能无法解决您的问题,但我在 Linux 上遇到了与 JPPF(通过 Java RMI)类似的问题。解决方案是确保客户端机器上的临时端口范围仅覆盖客户端本地防火墙允许的端口。例如,如果您的防火墙允许外部计算机连接端口 48000 到 64000,请确保您的临时端口范围也在 48000 到 64000 之间。试一试,让我们知道会发生什么。

于 2013-07-16T16:37:03.183 回答
-3
System.setProperty("java.rmi.server.hostname","10.0.3.73");

请在您的 RMIServer 端代码中使用上述语句,然后再次尝试从远程客户端连接。它对我有用

于 2016-12-16T05:01:09.083 回答