检查RMI连接的更好方法

sut*_*toL 5 java rmi

下面是检查另一侧RMI服务器是否在线的静态方法,我基本上调用了一个方法,如果它回答为true,则表示连接已打开;如果它不回答,而是给出异常,则表明出现问题。有更好的方法吗?有没有更好的方法来加快这一过程?如果存在连接,它将快速返回值,但是如果没有连接,则需要一段时间。

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;

}
Run Code Online (Sandbox Code Playgroud)

use*_*421 3

测试任何资源是否可用的最佳方法就是尝试使用它。这要么成功,要么失败,失败告诉您它不可用(或者出现其他问题)。

任何基于预先执行附加代码的方法都只是试图预测未来。它容易出现一些问题,其中包括测试错误以及测试和使用之间的状态变化。