Advertisement
khatta_cornetto

Mansi Ma'am 1st java 4 program

Feb 7th, 2025
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. 1. Remote Interface (MyRemoteInterface.java)
  2. import java.rmi.Remote;
  3. import java.rmi.RemoteException;
  4. public interface MyRemoteInterface extends Remote {
  5.  String sayHello() throws RemoteException;
  6. }
  7. 2. Remote Object (MyRemoteObject.java)
  8. import java.rmi.server.UnicastRemoteObject;
  9. import java.rmi.RemoteException;
  10. public class MyRemoteObject extends UnicastRemoteObject implements
  11. MyRemoteInterface {
  12.  
  13.  // Constructor
  14.  public MyRemoteObject() throws RemoteException {
  15.  super();
  16.  }
  17.  
  18.  // Implementation of the remote method
  19.  @Override
  20.  public String sayHello() throws RemoteException {
  21.  return "Hello from the remote object!";
  22.  }
  23. }
  24. 3. Server (Server.java)
  25. The server will create and register the remote object with the RMI registry.
  26. import java.rmi.Naming;
  27. import java.rmi.RemoteException;
  28. import java.rmi.registry.LocateRegistry;
  29. public class Server {
  30.  public static void main(String[] args) {
  31.  try {
  32.  // Start RMI registry on port 1099
  33.  LocateRegistry.createRegistry(1099);
  34.  // Create the remote object
  35.  MyRemoteObject remoteObject = new MyRemoteObject();
  36. // Register the remote object in the RMI registry with a
  37. name
  38.  Naming.rebind("RemoteHello", remoteObject);
  39.  System.out.println("Server is ready.");
  40.  } catch (Exception e) {
  41.  e.printStackTrace();
  42.  }
  43.  }
  44. }
  45. 4. Client (Client.java)
  46. The client will look up the remote object from the RMI registry and invoke its methods.
  47. import java.rmi.Naming;
  48. public class Client {
  49.  public static void main(String[] args) {
  50.  try {
  51.  // Look up the remote object by its name in the RMI registry
  52.  MyRemoteInterface remoteObject = (MyRemoteInterface)
  53. Naming.lookup("//localhost/RemoteHello");
  54.  // Call the remote method
  55.  String response = remoteObject.sayHello();
  56.  System.out.println("Server response: " + response);
  57.  } catch (Exception e) {
  58.  e.printStackTrace();
  59.  }
  60.  }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement