Java RMI – Intro and Example
Good Night,
Java RMI (Remote Method Invocation), is a mechanism that let the user, create distributed applications using Java. It takes care of Sockets, protocols and others. But how it works? All the magic is done by RMI. It have a server named RMIREGISTRY, where your server connect and says “I’m here”. After this Clients can connect to RMIREGISTRY and find the server that it wants.
I will show you an example of a Car Advertisement server, where Clients can add and search for Vehicle.
Server Interface
import java.rmi.RemoteException;
import java.util.List;
public interface MethosInterfaces extends Remote {
public List<Vehicle> search(String field, String value) throws RemoteException;
public void add(Vehicle v) throws RemoteException;
}
The methods in this interface will be implemented by our server, this interface extends Remote, it is a necessary class to make RMI works. All the methods must handle exceptions.
Server
Our Server that extends our Interface and implement the methods.
To create a new Server I used this:
try {
ServerAn server = new ServerAn();
MethosInterfaces stub = (MethosInterfaces) UnicastRemoteObject.exportObject(server, 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("Server", stub);
System.out.println("Servider running");
} catch (Exception ex) {
ex.printStackTrace();
}
}
We created a new ServerAN, export our server, and registry it with the bind.
Client Sender:
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost");
MethosInterfaces stub = (MethosInterfaces) registry.lookup("Server");
System.out.println("Sending new Vehicle to server");
stub.add(new Vehicle("Matheus2", 5000, "Caminhão", "", 2008));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Basically, we search by RMIREGISTRY in “localhost” and search by our server named “Server”, with the reference to it we add a new Vehicle. To search is almost the same thing but we will receive a List
Java RMI – Car Advertisement (Example)
Remember: rmiregistry search in your JAVA PATH and in the dir that you run it for the interfaces. So in this simple example, access the source folder, compile it, and then execute the RMIREGISTRY in the same dir. After this the server and then the clients. (All in the same this, you can use more than one prompt)
Matheus
PS: Java ME don’t come with RMI by default.
References:
http://infolab.stanford.edu/CHAIMS/Doc/Details/Protocols/rmi/rmi_description.html
http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136424.html
1 Comment
Other Links to this Post
-
RMI: Uma introdução a Java Remote Method Invocation | Processadores Dual Core — %A %B %e%q, %Y @ %I:%M %p
RSS feed for comments on this post. TrackBack URI





