Clients and servers communicate with each other via a registry running on the server computer.
The registry needs to be informed about instance that are to be accessed by
clients. Thus, to create a RatingServer
instance that is ready to
receive method calls from a client computer, you must establish a
connection with the server computer's running registry program.
The connection is done via a class method, rebind
, of the
Naming
class, which connects a name with a remotely accessible
instance. The rebind
method takes two arguments: one is a
host identifier, combined with a name of your
choice. The second is the remotely accessible instance.
The host identifier is a specification, such as whitney.ai.mit.edu
,
that specifies the computer on which the registry runs. Typically, this
computer is the same one on which the server runs, in which case the host
identifier is localhost
. The client uses a name of your
choicesuch as ratingService
to tell the registry
what the client seeks.
Because both rebind
and the RatingServer
constructor throw
exceptions, both the rebind
call and the RatingServer
construction must appear in a try
catch
combination.
import java.rmi.*;
import java.rmi.server.*;
public class RatingServer extends UnicastRemoteObject
implements RatingServerInterface {
public RatingServer () throws RemoteException {
super();
}
public int serverRating (MovieInterface m) throws RemoteException {
System.out.println("RatingServer asked for a rating");
int s = m.getScript();
int a = m.getActing();
int d = m.getDirection();
return 3 * Math.max(Math.max(s, a), d);
}
public static void main(String[] args) {
try {
Naming.rebind("//localhost/ratingService", new RatingServer());
System.out.println("Rating server connected to server");
}
catch (Exception e) {
System.err.println("RatingServer exception: " + e.getMessage());
e.printStackTrace();
}
}
}