Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. Remote Interface (MyRemoteInterface.java)
- import java.rmi.Remote;
- import java.rmi.RemoteException;
- public interface MyRemoteInterface extends Remote {
- String sayHello() throws RemoteException;
- }
- 2. Remote Object (MyRemoteObject.java)
- import java.rmi.server.UnicastRemoteObject;
- import java.rmi.RemoteException;
- public class MyRemoteObject extends UnicastRemoteObject implements
- MyRemoteInterface {
- // Constructor
- public MyRemoteObject() throws RemoteException {
- super();
- }
- // Implementation of the remote method
- @Override
- public String sayHello() throws RemoteException {
- return "Hello from the remote object!";
- }
- }
- 3. Server (Server.java)
- The server will create and register the remote object with the RMI registry.
- import java.rmi.Naming;
- import java.rmi.RemoteException;
- import java.rmi.registry.LocateRegistry;
- public class Server {
- public static void main(String[] args) {
- try {
- // Start RMI registry on port 1099
- LocateRegistry.createRegistry(1099);
- // Create the remote object
- MyRemoteObject remoteObject = new MyRemoteObject();
- // Register the remote object in the RMI registry with a
- name
- Naming.rebind("RemoteHello", remoteObject);
- System.out.println("Server is ready.");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- 4. Client (Client.java)
- The client will look up the remote object from the RMI registry and invoke its methods.
- import java.rmi.Naming;
- public class Client {
- public static void main(String[] args) {
- try {
- // Look up the remote object by its name in the RMI registry
- MyRemoteInterface remoteObject = (MyRemoteInterface)
- Naming.lookup("//localhost/RemoteHello");
- // Call the remote method
- String response = remoteObject.sayHello();
- System.out.println("Server response: " + response);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement