Hello.java
import java.rmi.Remote;
import java.rmi.RemoteException;
// Remote interface
public interface Hello extends Remote {
// Remote method declaration
String sayHello() throws RemoteException;
}
HelloImpl.java
Code:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
// Remote object implementation
public class HelloImpl extends UnicastRemoteObject implements Hello {
// Constructor (needed to throw RemoteException)
public HelloImpl() throws RemoteException {
super();
}
// Implementation of the remote method
public String sayHello() throws RemoteException {
return "Hello, Remote World!";
}
}
HelloServer.java
Code:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class HelloServer {
public static void main(String[] args) {
try {
// Create and export a remote object instance
HelloImpl helloObj = new HelloImpl();
// Get RMI registry on port 1099 (default)
Registry registry = LocateRegistry.createRegistry(6677ja);
// Bind the remote object's stub in the registry
registry.rebind("HelloService", helloObj);
System.out.println("Server is ready...");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
HelloClient.java
Code:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class HelloClient {
public static void main(String[] args) {
try {
// Get RMI registry on localhost, port 1099
Registry registry = LocateRegistry.getRegistry("localhost", 6677);
// Look up the remote object by the name
Hello helloObj = (Hello) registry.lookup("HelloService");
// Invoke the remote method
String response = helloObj.sayHello();
System.out.println("Response from Server: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Note: For it You have to Start the RMI registry (in a separate terminal or command prompt) using command :
start rmiregistry
Output:
No comments:
Post a Comment