javarmi

Java RMI in non-local environment


Im losing my mind, is there any clear documentation how to run java RMI between host and client remotly? i find in different forums, various puzzle pieces, but never, a from a to z guide, which scurity guidelines have to be followed etc, so that a RMI works. Well, if I run the server and client locally, it works.

Now, my low-level problem is that even if I set the external server address everywhere (?), in the error message it says that "localhost" has refused the connection.... Do you have any ideas?

Client:

        try {
        System.setProperty("java.rmi.server.hostname","42.155.241.914");
        String name = "RemoteBookService";
        String serverIP = "42.155.241.914"; // or localhost if client and server on same machine.
        int serverPort = 1099;
        Registry registry = LocateRegistry.getRegistry(serverIP, serverPort);

        IRemoteService rs = (IRemoteService) registry.lookup(name);

Error:

java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is: 
java.net.ConnectException: Connection refused: connect

Server:

public static void main(String[] args) throws MalformedURLException, AlreadyBoundException {
            
    try {
        System.setProperty("java.rmi.server.hostname","42.155.241.914");
        LocateRegistry.createRegistry(1099);
        String name="//42.155.241.914/RemoteBookService";
        RemoteService rs = new RemoteService();
        Naming.bind(name, rs);
        System.out.println("Service started");
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("could not start registry");
    }

}

Solution

  • At first glance it looks like your server uses LocateRegistry.createRegistry(port); which implies own registry (same process) which you don't store to local variable, and then you call Naming.rebind(bind, rs) which implies use of a local registry (same host, other process) on the default port.

    Try changing the lines on server to:

    Registry registry = LocateRegistry.createRegistry(port);
    ...
    // NOTE registry.rebind not called with name="//42.155.241.914/RemoteBookService"
    registry.rebind("RemoteBookService", stub); 
    

    Hopefully this may get you to the next step, but there are plenty of ways this could have gone wrong so you might need to edit the question with more details.