|
| | Here's the implement of the Hello server.
Notice that in this case the remote object and the remote server are the same
class.
package rmiServer;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import rmi.Hello;
/**
* Server for RMI Hello
*
* @author Bryan Higgs
* @version 1.0
*/
public class HelloServer implements Hello
{
public String sayHello() throws RemoteException
{
return "Hello, RMI world!";
}
/**
* Main entry point for server
* @param args the command line arguments
* args[0] contains the port number for the registry
*/
public static void main(String[] args)
{
// Determine the port number
int port = 1099; // the default port number for the registry
if (args.length > 0)
{
try
{
port = Integer.parseInt(args[0]);
}
catch (NumberFormatException nfe)
{
System.err.println("Port number " + args[1] + " invalid");
return;
}
}
try
{
// Create the object that provides the service
HelloServer object = new HelloServer();
// Export the remote object to the Java RMI runtime
Hello stub = (Hello) UnicastRemoteObject.exportObject(object, 0);
// Bind the remote object's stub in the RMI registry
Registry registry = LocateRegistry.getRegistry(port);
registry.bind("Hello", stub);
System.err.println("Server ready...");
}
catch (AlreadyBoundException abe)
{
// The attempt to bind failed, because it's already bound
abe.printStackTrace();
}
catch (RemoteException re)
{
re.printStackTrace();
}
}
}
|
Note that we:
- Export the remote object to the Java RMI runtime, using the java.rmi.server.UnicastRemoteObject
class's exportObject() method. This
causes a corresponding stub class to be loaded and an instance of that stub
class to be constructed
- Use the java.rmi.registry.LocateRegistry
class to locate the registry (on the server machine), and then java.rmi.registry.Registry
to bind the remote object in the RMI registry.
- If the object is already bound, then an AlreadyBoundException will
occur. Another possible choice is to call the rebind()
method to cause this binding to replace any already existing one.
- Implement the remote object in the sayHello()
method.
|