RMI:连接拒绝托管 - 编辑 /etc/hosts 和 setProperty() 不起作用

RMI: Connection refused to host - Editing /etc/hosts and setProperty() not working

我知道以前有人问过这个问题,但到目前为止我找到的答案没有帮助。我尝试通过添加行

来编辑我的 /etc/hosts-file
127.0.0.1    java.rmi.server.hostname

接下来,我尝试添加

System.setProperty("java.rmi.server.hostname","127.0.0.1");

到我的代码(也尝试使用我的 "external" IP 地址)。但是,我不断收到此错误:

java.rmi.ConnectException: Connection refused to host: 192.168.178.22; nested exception is: 
    java.net.ConnectException: Connection refused
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Naming.java:177)

这是我服务器的代码:

public class CounterServer {
    public static void main(String args[]) {
        try {
            System.setProperty("java.rmi.server.hostname","192.168.178.22");

            LocateRegistry.createRegistry(4711);

            ICounter counter = new Counter();
            Naming.rebind("Counter", counter);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

有什么办法可以解决这个问题吗?我在 运行 Mac OSX!

我的天,太蠢了 :-) 这个问题与 setProperty() 或我的 /etc/hosts 无关。当您从代码启动 RMI-Registry 时,请确保在该注册表而不是 Naming 上调用重新绑定。这是正确的代码,一切都运行得很好!

public class CounterServer {
    public static void main(String args[]) {
        try {    
            Registry r = LocateRegistry.createRegistry(4711);

            ICounter counter = new Counter();
            r.rebind("Counter", counter);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}