Search code examples
javamacosrmihosts

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


I know that this question has been asked before but the answers I found so far did not help. I tried editing my /etc/hosts-file by adding the line

127.0.0.1    java.rmi.server.hostname

Next, I tried adding

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

to my code (also tried with my "external" IP-Address). However, I keep getting this error:

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)

Here is my server's code:

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();
        }
    }
}

Any ideas how I can get this fixed? I am running on a Mac OSX!


Solution

  • Holy moly, so stupid :-) The problem had nothing to do with setProperty() or my /etc/hosts. When you start your RMI-Registry from code, make sure to call rebind on that registry and not on Naming. Here is the correct code and everything runs like a charm!

    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();
            }
        }
    }