Define remote interface
// Remote interface inherits from Remote
// The incoming parameter and return value of the remote method must be a natural type (int, float, boolean, etc.)
/ / Or the object of the Serializable or Remote interface is implemented.
Public interface time extends java.rmi.remote {
// Remote method must throw RemoteException:
Public string gettime () throws remoteException;
}
2. Define the implementation class
// Note: Implement the class inheritance from UnicastRemoteObject and custom remote interface Time:
Public class timeimpl extends java.rmi.server.UnicastRemoteObject implements time {
// Note: Due to the RemoteObject constructor, RemoteException is to be thrown.
/ / Sustably define the constructor and throw RemoteException:
Public TimeImpl () throws remoteException {super ();
/ / Here is a remote method:
Public string gettime () throws remoteexception {
Return "
12:04:27
"
}
// Start service:
Public static void main (string [] args) throws exception {
// You can start RMI Registry manually or start in the program:
Java.rmi.registry.locateRegistry.createREGISTRY (1099);
// Bind the name service, the address is the local computer name or native IP, the default port is 1099:
Java.rmi.naming.bind ("// localhost: 1099 / serviceename", new timeIMPL ());
// If there is no abnormality thrown, the bind is successful.
// If the name has been bound, you can replace the bound service with naming.rebind ().
}
}
3. Compile generation piles and frameworks
Run RMIC TimeImpl to generate TimeImpl_skel.class and TimeImpl_stub.class.
4. Client
// Client file contains client code client.class, remote interface Time.class,
// Supported by RMIC TimeImpl_skel.class and TimeImpl_stub.class:
Public static void main (string [] args) throws exception {
// The client can dynamically select the server through the remote object of the server side through the IP.
// If you do not specify a port, the default port number is 1099:
Time Time = (TIME) Java.rmi.naming.lookup ("// localhost: 1099 / serviceename");
System.out.println (Time.getTime ());
}