Reputation: 1767
below is a static method for checking if the other side RMI server is online, i basically call a method that if it replies true it means the connection is on, if it does not reply and instead gives a exception it means something is wrong. Is there a better way to do it? And is there a better way to speed up the process? If there is connectivity it returns with the value fast, but if not it takes sometime.
public static boolean checkIfOnline(String ip,int port)
{
boolean online = false;
try {
InetAddress ipToConnect;
ipToConnect = InetAddress.getByName(ip);
Registry registry = LocateRegistry.getRegistry(ipToConnect.getHostAddress(),port);
ServerInterface rmiServer = (ServerInterface)registry.lookup("ServerImpl");
online = rmiServer.checkStudentServerOnline();
if(online)
{
System.out.println("Connected to "+ipToConnect);
}
} catch (RemoteException e) {
System.out.println(e.getMessage());
//e.printStackTrace();
return false;
} catch (NotBoundException e) {
System.out.println(e.getMessage());
//e.printStackTrace();
return false;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return online;
}
Upvotes: 5
Views: 5149
Reputation: 310850
The best way to test whether any resource is available is simply to try to use it. That will either succeed or fail, and the failure tells you that it wasn't available (or something else went wrong).
Any approach based on executing additional code beforehand is merely attempting to predict the future. It is liable to several problems, among them testing the wrong thing and changes of status between the test and the usage.
Upvotes: 3