RMI-Example-1

RMI-Example-1

RMI-Example-1

RMI-Example-1

     

This is a very simple example of RMI where you will come to know how RMI works and what are the steps of executions. Here listed four java files and steps for executing this application.

Code:

RemoteInterface.java

import java.rmi.*;

public interface RemoteInterface extends Remote
{
  public int add(int x,int y)throws Exception;
}

ServerImplements.java

import java.rmi.*;
import java.rmi.server.*;
import java.lang.String;

interface RemoteInterface extends Remote
{
  public int add(int x,int y)throws Exception;
}

public class ServerImplements extends 
 
UnicastRemoteObject implements RemoteInterface
  {
  public ServerImplements()throws Exception
  {
  super();
  }
  public int add(int x,int y)
  {
  return (x+y);
  }
}

Server.java

import java.rmi.*;
import java.net.*;

public class  Server
{
  public static void main(String args[])
  {
  try
  {
  ServerImplements s=new ServerImplements();
  Naming.rebind("SERVICE",s);
  System.out.println("Server Started ");
  }
  catch(Exception e)
  {
  System.out.println(e.getMessage());
  }
  }

}

Client.java

import java.rmi.*;
import java.io.*;


public class Client
{
public static void main(String args[])
  {
 try
  {
 String ip="rmi://192.168.1.97/RMIAPPLICATION";
 RemoteInterface s=
   (RemoteInterface)Naming.lookup(ip);

 System.out.println("sum: "+ s.add(1,3));
  }
 catch(Exception e)
  {
  System.out.println(e.getMessage());
  e.printStackTrace();
  }
  }
}

Steps for executions

javac RemoteInterface.java

javac ServerImplements.java

rmic ServerImplements

javac Server.java

javac Client.java

start rmiregistry

start java server

java Client

Output:

Sum: 4