Creating a Java RMI Server
RMI
Java RMI (Remote Method Invocation) is a protocol that enables message transmission, including method calls, between distributed objects.
With RMI, you can build a server very simply without having to think about sockets.
You can also access the server almost as if you were using a local class.
To start the server, add permission java.security.AllPermission; to JAVA_HOME/jre/lib/security/java.policy.
Server interface
package com.devkuma.basic.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteServer extends Remote {
boolean isAlive() throws RemoteException;
}
Server implementation class
package com.devkuma.basic.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RemoteServerImpl extends UnicastRemoteObject implements RemoteServer {
public RemoteServerImpl(String name, int port) throws RemoteException {
System.setSecurityManager(new SecurityManager());
LocateRegistry.createRegistry(port);
try {
Naming.rebind(new StringBuffer(64).append("//:").append(port)
.append('/').append(name).toString(), this);
} catch (MalformedURLException e) {
throw new RemoteException(e.getMessage(), e);
}
}
public boolean isAlive() throws RemoteException {
return true;
}
public static void main(String[] args) {
try {
String serviceName = "devkuma";
int port = 1234;
new RemoteServerImpl(serviceName, port);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
Client class
package com.devkuma.basic.rmi;
import java.rmi.Naming;
public class RemoteServerClient {
public static void main(String[] args) {
try {
RemoteServer server = (RemoteServer) Naming.lookup("rmi:/localhost:1234/devkuma");
System.out.println(server.isAlive());
} catch (Exception e) {
e.printStackTrace();
}
}
}