i have problem that when i run my rmi server i got an exception notbound exception even i export the remote object and bind it to registry here is my remote interface code
import java.rmi.Remote;
public interface fact extends Remote {
public int factory(int a);
}
and here the interface implementation
public class factimport implements fact {
@Override
public int factory(int a) {
int mult=1;
for (int i=1;i<=a;i++)
mult=mult*i;
return mult;
}
}
and server code
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server extends UnicastRemoteObject {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Server() throws RemoteException {
super();
}
public static void main() throws RemoteException, MalformedURLException{
factimport fi=new factimport();
Registry reg=LocateRegistry.createRegistry(1099);
reg.rebind("factobject", exportObject(fi));
System.out.println("server started");
}
}
and client
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
/**
* @param args
* @throws NotBoundException
* @throws RemoteException
* @throws MalformedURLException
*/
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
// TODO Auto-generated method stub
Registry reg=LocateRegistry.getRegistry("127.0.0.1",1099);
factimport x=(factimport)reg.lookup("factobject");
System.out.println(x.factory(5));
}
}
Unless you're running the server and client on the same host, which makes RMI pretty pointless, your getRegistry()
call in the client needs to be modified to point to the server host, not the client host (itself).
Your remote method must be declared to throw RemoteException
in the remote interface.
Unless you have run rmic
on the remote interface, which you can't have done or you would have detected (2), you need to change the exportObject()
call to exportObject(fi, 0),
for reasons explained in the preamble to the Javadoc for UnicastRemoteObject.
Your Server.main()
method doesn't have a correct signature so it won't execute. It should be public static void main(String[] args) ...
You should make the Registry reg
variable in the server static to prevent it from being garbage-collected.
In your client, your variable of type factimport
should be of type fact
, and you should cast the lookup result to fact.
If the BindException
was really the result of running this code in this state on a single machine, it can only mean that you ignored runtime exceptions when starting the server.