Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Created March 5, 2015 07:51
Show Gist options
  • Save preslavrachev/59e5264e2634f6b78f25 to your computer and use it in GitHub Desktop.
Save preslavrachev/59e5264e2634f6b78f25 to your computer and use it in GitHub Desktop.
The following classes implement a simple client-server program using RMI that displays a message. Before running this example, we need to make a 'stub' file for the interface we used. For this task we have the RMI compiler - 'rmic' Note: we make a stub file from the '*.class' file with the implementation of the remote interface, not from the '*.…
import java.rmi.Naming;
public class RmiClient {
public static void main(String args[]) throws Exception {
RmiServerIntf obj = (RmiServerIntf)Naming.lookup("//localhost/RmiServer");
System.out.println(obj.getMessage());
}
}
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
public class RmiServer
extends UnicastRemoteObject
implements RmiServerIntf {
public static final String MESSAGE = "Hello World";
public RmiServer() throws RemoteException {
super(0); // required to avoid the 'rmic' step, see below
}
public String getMessage() {
return MESSAGE;
}
public static void main(String args[]) throws Exception {
System.out.println("RMI server started");
try { //special exception handler for registry creation
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
} catch (RemoteException e) {
//do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}
//Instantiate RmiServer
RmiServer obj = new RmiServer();
// Bind this object instance to the name "RmiServer"
Naming.rebind("//localhost/RmiServer", obj);
System.out.println("PeerServer bound in registry");
}
}
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RmiServerIntf extends Remote {
public String getMessage() throws RemoteException;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment