Search code examples
javarmi

Need help to better understand RMI


I am learning RMI and I have done something like:

Interface

import java.rmi.*;

public interface IRemote extends Remote {
    public void say() throws RemoteException;
}

Server

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

 public class Server extends UnicastRemoteObject implements IRemote{

     public Server() throws RemoteException{}

        public void say() throws RemoteException{
            System.out.println("I am saying Hello World...");
        } 

        public static void main (String[] argv) {
           try {
                          Naming.rebind ("myserver", new Server());
                          System.out.println ("Server is ready.");
            } catch (Exception e) {
                System.out.println ("Hello Server failed: " + e);
                  }
         }
     }

Client

  import java.rmi.*;

   class Client{
      public static void main(String args[]){
            try{
                  IRemote obj = (IRemote) Naming.lookup ("rmi://MYPCNAME/myserver");
                        obj.say();
                }catch(Exception e){
                System.out.println("Exception : "+e);
            }
       }
 }

And to run, I am first starting RMI registry.

start rmiregistry then java Server and then java Client

This thing is working fine when I am having all these three things in same package. But that is not what RMI is all about. I should be able to put Client on some other machine or other location and then call Server methods from there.

But when I do change package of Client.java and I try to compile it, I get the error:

Client.java:6: error: cannot find symbol IRemote obj = (IRemote) Naming.lookup ("rmi://MYPCNAME/myserver"); symbol: class IRemote location: class Client

It says it can't find IRemote, which is present in the package of Server. I want to know, how can I make this thing working properly? Both Client and Server on different packages or machines?


Solution

  • I suspect the problem is the lack of an import statement.

    When Client was in the same package as IRemote, you could refer to it without needing to import it. As soon as you moved the interface, your Client class no longer knew how to find it.