Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java RMI
package org.ivan.rmi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.AlreadyBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
/**
* User: ivan
* Date: 27.09.13
* Time: 17:19
*/
public class ServerEntryPoint {
public static void main(String[] args) {
try {
SimpleServer remoteObject = new SimpleServer();
Registry registry = LocateRegistry.createRegistry(1099);
Remote skeleton = UnicastRemoteObject.exportObject(remoteObject, 0);
registry.bind(SimpleRemote.REMOTE_NAME, skeleton);
System.out.println("[INFO]: Service started");
listenConsole();
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
public static void listenConsole() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line;
while((line = br.readLine()) != null) {
if(line.toLowerCase().contains("exit")) {
System.out.println("Bye!");
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.ivan.rmi;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Random;
/**
* User: ivan
* Date: 27.09.13
* Time: 13:14
*/
public class SimpleClient {
public static void main(String[] args) {
Random rand = new Random();
try {
SimpleRemote proxy = (SimpleRemote) LocateRegistry.getRegistry(1099).lookup(SimpleRemote.REMOTE_NAME);
for(int i = 0; i < 5; i++) {
int a = rand.nextInt(100);
int b = rand.nextInt(100);
System.out.format("%d + %d = %d\n", a, b, proxy.sum(a, b));
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
package org.ivan.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* User: ivan
* Date: 27.09.13
* Time: 13:03
*/
public interface SimpleRemote extends Remote {
String REMOTE_NAME = "SUMMATOR";
int sum(int i, int j) throws RemoteException;
}
package org.ivan.rmi;
/**
* User: ivan
* Date: 27.09.13
* Time: 13:06
*/
public class SimpleServer implements SimpleRemote {
@Override
public int sum(int i, int j) {
return i + j;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.