MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create RMI client and server to invoke remove method of RMI server in java

In this article, we shall learn the very important feature of java networking that helps to accessing the methods running on the server by the client.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

The java concept RMI, stands for Remote Method Invocation made it very easy the client to access a method on server, which is known as remote method invocation.

Objective: The main objective of RMI is to provide the facility of invoking method on server. This is done by creating a RMI Client and RMI Server. RMI Client invokes a method defined on the RMI Server. In this article, we will learn:

  • What is RMI (Remote Method Invocation)?
  • How do we in invoke a method running in differ JVM from another JVM
  • How to write an application using RMI methodology

RMI Terminology:

Method is invoked by client on the server using RMI

Figure 1: Method is invoked by client on the server using RMI

RMI is used to communicate between two running java applications on different JVM (Java Virtual Machines). The main motive behind RMI implementation is to invoke one method running on different JVM. The JVM Application, in which an invoked method is running out, is called RMI Server, where as the invoking application running on the different JVM is called RMI Client.

Remote Obj / RMI Server: It is an object that exposes methods which can be invoked by Remote Client using RMI.

RMI Client: It is an object that invokes remote methods on an RMI Server.

Stub: A stub is proxy that stands for RMI Server on client side and handles remote method invocation on behalf of RMI Client.

Skeleton: It is a proxy that stands for RMI client on server side and handles remote method invocation on RMI Server on behalf of client.

Registry Service: A Registry Service is an application that provides the facility of registration & lookup of Remote stub.

A Registry Service provides location transparency of Remote Object to RMI Client.

Steps:

Define a Remote Interface that contains methods which can be remotely invoked on remote object. Each Remote Interface have to extend

java.rmi.Remote

Interface and each remote method declared in the remote interface have to throw java.rmi.RemoteException.

Lisiting 1: Define Remote Interface, declaring Remote Method

import java.rmi.*;
public interface HelloInterface	 extends Remote {
	public String say(String msg, int a, int b) throws RemoteException;
               }

Let’s define a class for representing remote object. This class must implement remote interface created in the first point and this class is also responsible for created Stub and Skeleton objects.

In order to provide functionality of creating stub and skeleton object, this class must be extended by UnicastRemoteObject and this class must have a default constructor throwing RemoteException.

Listing 2: Defining Hello class that extends and implements UnicastRemoteObject and HelloInterface

import java.rmi.*;
import java.rmi.server.*;
public class Hello
	extends UnicastRemoteObject
	implements HelloInterface {
		private String message;
		public Hello(String msg) throws RemoteException {
			message = msg;
		}
		public String say(String m, int a, int b) throws RemoteException {
			String str = "";
			switch(m.charAt(0)){
				case 'a':
					str = "Addtion : " + add(a,b);
				break;
				case 's':
					str = "Substraction : " + sub(a,b);
				break;
				case 'm':
					str = "Multiplication : " + mul(a,b);
				break;
				case 'd':
					str = "Division : " + div(a,b);
				break;
				default:
					str = "Wrong Operation";
			}
			return str;
		}
		public int add(int a, int b){
			return a+b;
		}
		public int sub(int a, int b){
			return a-b;
		}
		public int mul(int a, int b){
			return a*b;
		}
		public int div(int a, int b){
			return a/b;
		}
	}

Generate Stub & Skeleton classes using rmic tool:

rmic <remote-class>

Listing 3: How to compile and generate Stub and Skeleton Classes

javac HelloInterface.java Hello.java
rmic Hello

Start Registry Services using rmiRegistry tool:

rmiRegistry <port-number>

or

rmiRegistry

Create an object of RMI server and register its stub in the RMI registry. Java.rmi.Naming class provide static method for registration in the lookup of rmiStub.

bind() : This method is used to register a remote object (stub of object) in the rmiRegistry.

Syntax: public static void bind(String name, Remote object) throws RemoteException, AlreadyBindException

rebin(): This method is used to rebind the remote object in the rmiRegistry.

Syntax: Public static void rebind(String name, Remote object) throws RemoteException

Lookup() : This method is used to lookup remote stub in the rmiRegsitry.

Syntax: Public static Remote lookup(String name) throws RemoteException

Listing 4: Define a RMI Server Class

import java.rmi.*;
import java.rmi.server.*;
public class HelloServer {
	public static void main(String argv[]) {
		try {
			  Naming.rebind ("Hello", new Hello ("Hello, world!"));
			  System.out.println ("Hello Server is ready.");
		} catch (Exception e) {
		  System.out.println ("Hello Server failed: " + e);
		}
	}
}

Now define a RMI Client. A RMI Client has to obtain the refrence of remote stub from the RMI registry and invokes remote method.

Listing 5: Define a RMI Client Class

import java.rmi.*;
public class HelloClient {
	public static void main(String args[]) {
		try {
			if (args.length < 0) {
				System.err.println("usage: java HelloClient string …\n");
				System.exit(1);
			}
			HelloInterface hello = (HelloInterface)Naming.lookup("//localhost/Hello");
			System.out.println(hello.say(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])));
		}
		catch (Exception e) {
			System.out.println("Helloclient exception: " + e);
		}
	}
}

If RMI registry is running on non-default port on a different machine, then following steps are required for registration:

Java.rmi.registry.LocateRegistry class is used to create a registry object. This class provide following methods:

Public static Registry getRegistry (int port);
Public static Registry getRegistry(String host, int port);

Java.rmi.registry.Registry class provides bind() and lookup() methods for registration & lookup of remote stub in a registry.

Listing 6: Define how to register a server in Registry if RMI Registry run on non default port

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RegisterServer {
	public static void main(String[]args){
		try{
			System.out.println("Createing A RMI Server..");
			ServerClass serverObject = new ServerClass();
			System.out.println("Register created RMI Server..");
			Registry registerObj = LocateRegistry.getRegistry("localhost", 5000);
			//The next statement will throw AlreadyBoundException, that will be caught by catch statement of class AlreadyBoundException
			registerObj.bind("serverclass", serverObject);
			System.out.println("Stub Registered, Server is ready..");
		}
		catch(RemoteException e){
			e.printStackTrace();
		}
		catch(AlreadyBoundException e){
			e.printStackTrace();
		}
	}
}

Info regarding RMI registry is provided to lookup() method through “Lookup String”. Lookup string has the following format:

LookupString:

“protocol:hostname:portNo/registeredNameserver”

Listing 7: If RMI Registry run on non default port, define a RMI Client

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class MyClient {
public static void main(String[]args){
	try {
		/*
		 * Following statement may throw three kinds of exceptions:
		 * @ MalformedURLException
		 * @ RemoteException
		 * @ NotBoundException
		 * 
		 */
		
		Naming.lookup("rmi://localhost:3000/serverclass");
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NotBoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

Compile RMI Client and Server Classes and Interface

  • First of all compile all the classes and interface using javac command: javac *.java
  • Now generate stub class file from remote method class that implements Remote Methods using rmic tool for remote : rmic hello
  • Now start rmiregistry in one console:
Start rmiregistry in command window as shown in figure using command rmiregistry

Figure 2: Start rmiregistry in command window as shown in figure using command rmiregistry

In the above figure, RMI Registry is shown running on its default port 1022. We can also rmiregistry on different port using rmiregistry <port-no>.

Now start RMI server in new console as shown in figure:

Star RMI server using java server-class-name command as shown in figure

Figure 3: Star RMI server using java <server-class-name> command as shown in figure

Above figure shows, how to start RMI server. Java <rmi-server-class-name> & is placed in the command window to start rmi server.

Now start a RMI client using java <client-class-name> and command line arguments, if needed as shown in figure:

Calling remote method running on rmi server using rmi client

Figure 4: Calling remote method running on rmi server using rmi client

Above figure shows that HelloClient call remote method to perform arithmetic operation to add two numbers. Three arguments are passed as command line argument those are manipulated on these server in the remote method implemented and process results of two numbers as string:

Addition : 2

Conclusion:

In this article, we learn:

  • What is RMI
  • Why do we need RMI
  • How to create RMI Server and Client to invoke Remote Methods


Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login