Hello World RMI using Netbeans
August 15, 2012 7 Comments
While working on my assignment for the Sun Certified Developer for the Java 2 Platform certification, I discovered that little documentation exists for setting up a simple Remote Method Invocation (RMI) hello world application using Netbeans.
Hopefully this post saves others time that I had to invest. The code here heavily leverage’s that available on Rose India, however, the code on Rose India did not work without modification.
1. Create an Interface named HelloInterface that extends Remote:
import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
2. Create a class Hello which implements 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() throws RemoteException {
return message;
}
}
3. Create a class named HelloServer which, believe it or not, acts as the server. This class creates an entry in the servers RMI registry which is available for the client.
import java.rmi.Naming;
import java.rmi.registry.Registry;
public class HelloServer {
public static void main(String[] args) {
try {
Registry r = java.rmi.registry.LocateRegistry.createRegistry(1099);//1099 is the port number
r.rebind("Hello", new Hello("Arsenal Football Club, THFC forever in our shadow."));
System.out.println("Server is connected and ready for operation.");
} catch (Exception e) {
System.out.println("Server not connected: " + e);
}
}
}
4. Write your client class, HelloClient, which invokes the remote methods on your server:
import java.rmi.Naming;
public class HelloClient {
public static void main(String[] argv) {
try {
HelloInterface hello = (HelloInterface) Naming.lookup("//localhost/Hello");
System.out.println(hello.say());
} catch (Exception e) {
System.out.println("HelloClient exception: " + e);
}
}
}
That is all your coding coded. Now run the server, then run the client. There lies the foundation for you to take over the world using RMI. As a special bonus, enjoy a picture of Tony Adams.
Also, as a little link juice to another site of mine, here is a reminder for an online booking system named BookingHawk.com.
Pingback: RMI-generazione-dinamica-degli-stub-e-skeleton | mauroprogram's Blog
Wonderful post! Thanks for saving my time 🙂
Hi Sarah. I am glad you found it useful. Its an old post but its still the most popular on the site. Good Luck with your RMI 🙂
Thanks for Your Service
Very helpful..thanks alot
The following error is returned:
HelloClient exception: java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
java.io.EOFException
very nice code. very very clean. i am running it in netbeans. running perfectly