Implementation of Remote
Interface
Now you must create a server implementation of the remote interface
(HelloInterface).
Responsibilities of a remote object implementation class:
- The class must implement at least one remote interface. It is possible
for a single class to implement more than one remote interface.
- Define the constructor(s) for the remote object and declare its
constructor(s) to throw RemoteException
.
- Provide implementation for the methods that may be invoked by the
client remotely.
- Export the object by extending the
UnicastRemoteObjec class or use the exportObject()
method of the same class.
In this example, the server class (HelloServerImpl)
will implement the remote interface (HelloInterface)
and extend UnicastRemoteObject
(See Figure 3.1).
Figure 3.1
Listing 3.2 HelloServerImpl.java (Complete server code)
import java.rmi.*;
import java.rmi.server.*;
import java.net.MalformedURLException;
//server class
public class HelloServerImpl
extends UnicastRemoteObject
implements HelloInterface{
//constructor
public HelloServerImpl()
throws RemoteException {
System.out.println("Creating server Object");
}
//remote method called by clients
public String getMessage()
throws RemoteException {
return "Hello World";
}
//main method
public static void main(String []helloWorld) {
try {
//create a server object
HelloServerImpl helloServer = new HelloServerImpl();
//bind the server
Naming.rebind("Server",helloServer);
System.out.println("Server Ready");
}catch(RemoteException ex) {
System.out.println("Error " +ex.getMessage());
}
catch(MalformedURLException ex) {
System.out.println("Error " +ex.getMessage());
}
}
}
|