Search code examples
javarmi

import/package issue with RMI


I have two packages client and server:

enter image description here

the client package contains an interface "I_object":

package client;

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface I_object extends Remote {  

public int Add(int a,int b) throws RemoteException;

}

and a class main_client:

package client;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

/**
*
* @author marwen
*/

public class main_client {


public static void main(String [] args) throws NotBoundException,  MalformedURLException, RemoteException{

 I_object obj_distant=(I_object) Naming.lookup("rmi://localhost:1000/exemple");

 System.out.println(obj_distant.Add(5, 9));    

}
}

The server package contains a class(impl_object ) that implements the interface I_object:

package server;

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;


/**
*
* @author marwen
*/
public class impl_object  extends UnicastRemoteObject implements I_object {

public impl_object() throws RemoteException
{}

public int Add(int a,int b) throws RemoteException{
return a+b;
}

}

and finally a main_server:

package server;

import java.net.MalformedURLException;

import java.rmi.Naming;

import java.rmi.NotBoundException;

import java.rmi.RemoteException;


public class main_server {

public static void main(String [] args) throws NotBoundException, MalformedURLException, RemoteException{

    impl_object obj=new impl_object();

   java.rmi.registry.LocateRegistry.createRegistry(1000);

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

 System.out.println("server is running");
}
}

if you noticed in the implementation of "impl_object" , i have not put an "import client.I_object;" why??????? okay , precisely, if I put an "import client.I_object;" to the client package, So the server will be "linked" to the client !!! that's the problem , When I separate the client and the server (I put the server on a remote computer and the client at home)???.... Can someone explain to me, I'm wrong?


Solution

  • EDITED ANSWER:

    You can your interface and impl class into a separate package like model and then import them from this package if you like. Impl object is the object used by both server and client it doesn't bind them in this way (client only way). It's UnicastRemoteObject to be used with JRMP and they both have to be aware of this object.