Java RMI Hello World example

RMI stands for Remote Method Invocation and it is the object-oriented equivalent of RPC (Remote Procedure Calls). RMI was designed to make the interaction between applications using the object-oriented model and run on different machines seem like that of stand-alone programs.

The code below will give you the basis to Java RMI with a very simple example of a Server-Client communication model.

1. The Remote Interface

The first thing we have to design is the Remote Interface that both Server and Client will implement. The Interface must always be public and extend Remote. All methods described in the Remote interface must list RemoteException in their throws clause.

Our RMIInterface has only one method; it receives a String parameter and returns String.

RMIInterface.java

package com.mkyong.rmiinterface;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RMIInterface extends Remote {

    public String helloTo(String name) throws RemoteException;

}

2. The Server

Our Server extends UnicastRemoteObject and implements the Interface we made before. In the main method we bind the server on localhost with the name “MyServer”.

ServerOperation.java

package com.mkyong.rmiserver;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import com.mkyong.rmiinterface.RMIInterface;

public class ServerOperation extends UnicastRemoteObject implements RMIInterface{

    private static final long serialVersionUID = 1L;

    protected ServerOperation() throws RemoteException {

        super();

    }

    @Override
    public String helloTo(String name) throws RemoteException{

        System.err.println(name + " is trying to contact!");
        return "Server says hello to " + name;

    }

    public static void main(String[] args){

        try {

            Naming.rebind("//localhost/MyServer", new ServerOperation());            
            System.err.println("Server ready");

        } catch (Exception e) {

            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();

        }

    }

}

3. The Client

Finally, we create the Client. To “find” the Server, the Client uses an RMIInterface Object that “looks” for a reference for the remote object associated with the name we pass as parameter. With that RMIInterface object we can now talk to the Server and receive responses.

File: ClientOperation.java

package com.mkyong.rmiclient;

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

import javax.swing.JOptionPane;

import com.mkyong.rmiinterface.RMIInterface;

public class ClientOperation {

	private static RMIInterface look_up;

	public static void main(String[] args) 
		throws MalformedURLException, RemoteException, NotBoundException {
		
		look_up = (RMIInterface) Naming.lookup("//localhost/MyServer");
		String txt = JOptionPane.showInputDialog("What is your name?");
			
		String response = look_up.helloTo(txt);
		JOptionPane.showMessageDialog(null, response);

	}

}

4. How to run it

4.1 Create the three java files with your favorite IDE or Download the code below. Navigate to your source folder as shown below.

java-rmi-hello-9a

4.2 First thing we need to do is compile our sources. Run compileEverything.bat if you downloaded the code below or open a command window at your directory and run:

Terminal

javac src/com/mkyong/rmiinterface/RMIInterface.java src/com/mkyong/rmiserver/ServerOperation.java src/com/mkyong/rmiclient/ClientOperation.java

4.3 Confirm that your sources were compiled by accessing their respective directories:

java-rmi-hello-9b

4.4 Next we need to start the rmiregistry. Again either run the startServer.bat or open a command window and run:

Terminal

cd src
start rmiregistry
java com.mkyong.rmiserver.ServerOperation
java-rmi-hello-9c

4.5 If RmiRegistry started successfully, there will be another window that looks like this:

java-rmi-hello-9d

4.6 Now we are ready to run our Client:

Open a new command prompt window (or run the runClient.bat from the downloaded files) and run this:

Terminal

cd src
java com.mkyong.rmiclient.ClientOperation

The ClientOperation runs and prompts us for input:

java-rmi-hello-9e

We type a name in the input field (ex. “Marilena”) and click “OK”

4.7 On Server side we can see this:

java-rmi-hello-9f

4.8 And on the Client side this:

java-rmi-hello-9g

4.9 The client closes after the exchange is over, while the server stays on and we can communicate again if we run the client file again. Indeed, we run the client again and:

java-rmi-hello-9h

Server :

java-rmi-hello-9i

Client :

java-rmi-hello-9j

Download Source Code

Download it – SimpleRmiExample.zip (4 KB)

References

  1. RMI – Indiana University
  2. Remote – Java API
  3. UnicastRemoteObject – Java API

About the Author

author image
Marilena
Marilena Panagiotidou is a senior at University of the Aegean, in the department of Information and Communication Systems Engineering. She is passionate about programming in a wide range of languages. You can contact her at an3liram@gmail.com or through her LinkedIn.

Comments

Leave a Reply

avatar
newest oldest most voted
Adnan Raza
Guest
Adnan Raza

java.lang.ClassNotFoundException: com.mkyong.rmiinterface.RMIInterface

Filip
Guest
Filip

On command prompt window type: cd /path-to-directory-with-compiled-classes , this directory contains all *.class files in your project. When youre in this directory try java className.

RMI New Bee
Guest
RMI New Bee
Any Solution for these please. java com.mkyong.rmiserver.ServerOperation Server exception: java.rmi.ConnectException: Connection refused to host: localho st; nested exception is: java.net.ConnectException: Connection refused: connect java.rmi.ConnectException: Connection refused to host: localhost; nested excepti on is: java.net.ConnectException: Connection refused: connect at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619) at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216 ) at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202) at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) at java.rmi.Naming.rebind(Naming.java:177) at com.mkyong.rmiserver.ServerOperation.main(ServerOperation.java:24) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI mpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja va:345) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket Impl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java :188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at java.net.Socket.(Socket.java:434) at java.net.Socket.(Socket.java:211) at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirect SocketFactory.java:40) at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMaster SocketFactory.java:148) at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.j
gaurav
Guest
gaurav

I am also getting same error, can anybody please help us.

donhk
Guest
donhk

for those who are having issues with java.lang.ClassNotFoundException
make sure you execute rmiregisrty from the top directory of the compiles sources
/build/classes/, /out/producction/ or whatever it is called on your system like if it were a classpath

Srijit Paul
Guest
Srijit Paul

Useful, simple and clean. Thanks

marc
Guest
marc

I have a wierd behavior. One prompt execute the server and it write server ready. Then I start a new prompt for the client. But when I send the name, the gui window close but nothing happen on the server side. So anyone have an idea where it come from.
Thank you

Andrey Stepanov
Guest
Andrey Stepanov

Thank you for the great introduction to the subject.

Just to clarify.
“… the Remote Interface that both Server and Client will implement”
It looks like the ClientOperation DOES NOT implement the RMIInterface

xx xxxxbbb
Guest
xx xxxxbbb

I have the same problem

Nalini De Souza
Guest
Nalini De Souza

Exception in thread “main” java.lang.NullPointerException
at ClientOperation.main(ClientOperation.java:19)
What to do to solve this error

Andrey Stepanov
Guest
Andrey Stepanov

Did you start the server?
After the server is started in its own window (one – for the server, another – for the client) you must read in the server window: “Server ready”