Home > Programming, Technology > RMI in Java

RMI in Java


In this post I’m going to write how I did RMI using java. This RMI program finds the current time of the server (on which the remote method is executed).

While implementing RMI in java we have to follow several steps.

step1: Create an interface which specifies what service server is going to provide or implement

/**
 *
 * @author Vasanth Raja Chittampally
 */

import java.rmi.*;
public interface TimeatServer extends Remote{
 public String showTime() throws RemoteException;
}

The above TimeatServer is an interface which is extending java.rmi.Remote contains the showTime() function which has to be defined in the server class. java.rmi.Remote specifies the the showTime() as the remote method which can be called from any virtual machine. All the methods which are declared inside the remote interface(An interface which has extended the java.rmi.Remote interface) are available Remotely.

step 2: Now we have to code the server implementation of above written TimeServer interface.

import java.rmi.*;
import java.rmi.server.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
 *
 * @author Vasanth Raja Chittampally
 */
public class TimeServerImpl extends UnicastRemoteObject implements TimeatServer{
    public TimeServerImpl() throws Exception {

    }

    public String showTime() throws RemoteException {
        Calendar calendar = new GregorianCalendar();
    String am_pm;
    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
    else
      am_pm = "PM";
    return "Current Time : " + hour + ":"
+ minute + ":" + second + " " + am_pm;
    }
}

The above TimeSeverImpl.java extends the java.rmi.UnicastRemoteObject and implements the TimeServer interface. All the remote objects must extend UnicastRemoteObject because it provides the functionality through which the object becomes available from the remote machines.

step 3: In this step we have to bind the server implementation of the service with the service name

import java.rmi.*;
import java.rmi.server.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Vasanth Raja Chittampally
 */
public class BindServer {
    public static void main(String[] args) {
        try {
            TimeServerImpl tsi= new TimeServerImpl();
            Naming.bind("time", tsi);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

In the above file we are binding the AddServerImpl object with the service name of “time”.
java.rmi.Naming.bind() function binds the service name with the service object.

step 4: Create client


import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vasanth Raja Chittampally
*/
public class Client {
    public static void main(String[] args) throws NotBoundException {
        try {
            String url="rmi://127.0.0.1/time";
            TimeatServer ts=(TimeatServer) Naming.lookup(url);
             System.out.println(""+ts.showTime());
        } catch (MalformedURLException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Client(Client.java) has to specify the url where exactly the server is available that is specified as a string using rmi://IP_ADDRESS/SERVICE_NAME. In the above example it was rmi://127.0.0.1/time.

127.0.0.1 specifies the localhost and time is the service with which we have bound the service in the BindServer.java file.

java.rmi.Naming.lookup() actually looks up for the service with the string specified in it, if it finds a service with the specified string then it returns its object. Using the returned object we are calling remote method showTime().
step 5: compile all the files till now we have create using standard javac command.

step 6: Generate the stubs

We actually need to have client stub and server stub. We first have to create stubs.

Here we can create only one stub.

In order to create the stub we have to compile using the RMI complier.

type

rmic -v1.1 TimeServerImpl

in the command prompt

then it creates two files TimeServerImpl_Stub.class and TimeServerImpl_Skel.class.

step 7:

now copy Client.class, TimeServer.class and TimeServerImpl_Stub.class into the client side machine.

copy all files except for the Client.class into the server machine.

Note: You can ignore the step 7 for the first time.

step 8: Now we have start the rmiregistry. Now let us go a little into the theory part. First server program binds the services to the binding registry. Client internally client stub checks for the service, if finds one, sends the marshalled parameters to the server stub. Now server stub unmarshalls the packaged parameters and calls the function then the returned results are marshalled or packaged by the server stub and sent to the client stub. now client stub unmarshalls the returned results and the remaining program will be executed at the client side.

inorder to register the services we have a tool called rmiregistry which is available from Java 2 SDK. open the terminal or command prompt and type

start rmiregistry

now you can see a separate window.

step 9: Run the BindServer.java program

using

java BindServer

step 10: Run the Client.java program

java Client

Output:

Current Time : 4:28:33 PM

Advertisements
  1. Ankit Gupta
    May 21, 2011 at 11:10 am

    It works perfectly well…
    That was a great help !!
    Thanks a lot
    🙂

  2. October 18, 2011 at 7:53 am

    good job ra..:-)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: