Recently I started with Java again, but I’m am quite stuck with RMI. I have managed to get it working with a voided function, but it seems to be unable to return a String over the network.
Does anyone know what I am doing wrong?
Main.java:
package RMI;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Random;
public class Main extends UnicastRemoteObject implements Main_Interface {
private Random random;
private boolean coin = false;
public Main() throws RemoteException { ; }
public String flipCoin() throws RemoteException {
coin = random.nextBoolean();
if(coin) {
System.out.println("Throwing Head");
return "Head";
} else {
System.out.println("Throwing Tail");
return "Tail";
}
}
public void test() throws RemoteException {
System.out.println("Test succesful");
}
}
Main_Interface.java:
package RMI;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Main_Interface extends Remote {
String flipCoin() throws RemoteException;
void test() throws RemoteException;
}
Client.java (stripped from the unimportant code):
package Client;
import RMI.Main_Interface;
import java.io.*;
import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
String line = null;
boolean coin = false;
Main_Interface conn = null;
try {
String location = InetAddress.getLocalHost().getHostName();
Registry myRegistry = LocateRegistry.getRegistry(location, 1099);
conn = (Main_Interface) myRegistry.lookup("ISA");
//conn = (Main_Interface) Naming.lookup("ISA");
} catch (Exception e) {
System.out.println("Server could not be found at "+location);
System.exit(0);
}
try {
conn.test()
System.out.println("Here");
if(conn.flipCoin().equals("Head")){
System.out.println("Succes");
}
System.out.println("Here");
if(coin) {
System.out.println("Throwed Head");
} else {
System.out.println("Throwed Tail");
}
} catch (Exception e) {
System.out.println("Could not execute the command...");
}
}
}
As you can probally guess, the test() function will be executed perfectly, but the flipCoin() function will throw the exeption.
What kind of Exception is thrown exactly?
If it’s a NullPointerException: You never initialize
randomin yourMainclass. Put something likerandom = new Random();in your constructor