Java Remote Objects


Topics interesting only for Java programmers

Link to this posting

Postby Ursego » 05 Mar 2019, 07:49

To see the keywords colored, save the following text in a text file and open it in a Java compiler (or in Notepad++ and select in the menu: Language > J > Java).

Code: Select all
// @@@@@@@ Define the remote interface:
// A remote object is an instance of a class that implements a remote interface. A remote interface extends the interface java.rmi.Remote and declares a set of remote methods.
public interface Remote
// The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.

// Each remote method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions. Remote method invocations can fail in many additional ways compared to local method invocations (such as network-related communication problems and server problems), and remote methods will report such failures by throwing a java.rmi.RemoteException. Here is the interface definition for the remote interface used in this example, example.hello.Hello. It declares just one method, sayHello, which returns a string to the caller:
package example.hello;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Helloable extends Remote {
    String sayHello() throws RemoteException;
}

// @@@@@@@ Implement the server:
// A "server" class, in this context, is the class which has a main method that creates an instance of the remote object implementation, exports the remote object, and then binds that instance to a name in a Java RMI registry. The class that contains this main method could be the implementation class itself, or another class entirely. In this example, the main method for the server is defined in the class Server which also implements the remote interface Helloable (providing an implementation for the remote method sayHello):

package example.hello;
       
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
       
public class Server implements Helloable {
    public Server() {}

   // The method sayHello does not need to declare that it throws any exception because the method implementation itself does not throw RemoteException nor does it throw any other checked exceptions:
    public String sayHello() { return "Hello from the server!"; }

    public static void main(String args[]) {
        try {
         // Create the remote object that provides the service:
            Server server = new Server();

         // Export the remote object to the Java RMI runtime to make it available to receive incoming calls. That is done by the following static method of UnicastRemoteObject,
         // which returns a stub that communicates to the remote object returns (the stub for the remote object to pass to clients) (stub = proxy in this context):
         //       public static Remote exportObject(Remote obj, int port) throws RemoteException
         // The returned stub implements the same set of remote interfaces as the remote object's class and contains the host name and port over which the remote object can be contacted:
            Helloable remoteObjectStub = (Helloable) UnicastRemoteObject.exportObject(server, 0);
         // As a result of exportObject, the runtime may begin to listen on a new server socket or may use a shared server socket to accept incoming remote calls for the remote object.

            // A Java RMI registry is a simplified name service that allows clients to get a reference (a stub) to a remote object. In fact, the registry is a dictionary (hash table). The names used for bindings in a Registry
         // are pure strings, not parsed. A service which stores its remote reference in a Registry may wish to use a package name as a prefix in the name binding to reduce the likelihood of name collisions in the registry.

         // Registry is a remote interface to a simple remote object registry that provides methods for storing and retrieving remote object references bound with arbitrary string names (the bind, unbind, and rebind methods).
         //       public interface Registry extends Remote
         // The static method LocateRegistry.getRegistry() returns a stub that implements the remote interface java.rmi.registry.Registry and sends invocations to the registry on server's
         // local host on the default registry port of 1099. Obtain a stub for a registry on the local host and default registry port (i.e. create a local reference to the remote registry):
            Registry registry = LocateRegistry.getRegistry(); // no arguments to getRegistry() = local host; other overloads: getRegistry(int port), getRegistry(String host), getRegistry(String host, int port)

         // The bind() method of Registry interface binds a reference to a remote object (usually a stub) to the specified name in this registry:
         //       void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException, AccessException

         //  Bind the remote object's stub (i.e. register the remote object) in the Java RMI registry (so, the stub will be accessible by the key "Hello"):
            registry.bind("example.hello.Hello", remoteObjectStub);
         // Once a remote object is registered on the server, callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object.

            System.err.println("Server is ready");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
    }
}
// Note: A class can define methods not specified in the remote interface, but those methods can only be invoked within the virtual machine running the service and cannot be invoked remotely.

// @@@@@@@ Implement the client
// The client program obtains a stub for the registry on the server's host, looks up the remote object's stub by name in the registry, and then invokes the sayHello method on the remote object using the stub:

package example.hello;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {
    private Client() {}
    public static void main(String[] args) {
        String serverHostName = (args.length < 1) ? null : args[0]; // if no hostname is passed in, then null is used indicating that the local host address should be used
        try {
            Registry registry = LocateRegistry.getRegistry(serverHostName); // this time - the getRegistry(String host) overload

         // Obtain the stub for the remote object from the server's registry:
            Helloable remoteObjectStub = (Helloable) registry.lookup("example.hello.Hello");

         // Invoke the sayHello() method on the remote object's stub, which causes the following actions to happen:
         // 1. The client-side runtime opens a connection to the server (using the host and port information in the remote object's stub) and then serializes the call data.
         // 2. The server-side runtime accepts the incoming call, dispatches the call to the remote object, and serializes the result (the string "Hello from the server!") to the client.
         // 3. The client-side runtime receives, deserializes, and returns the result to the caller.
            String response = remoteObjectStub.sayHello();

            System.out.println("Response: " + response);
        } catch (Exception e) {
            System.err.println("Client exception: " + e.toString());
            e.printStackTrace();
        }
    }
}
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker