检查RMI连接的更好方法

5
以下是一种用于检查对方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;

}

2
你的“ping”式方法在我看来是合理的。 - Anonymous
1个回答

3

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

任何基于事先执行额外代码的方法只是试图预测未来。它容易出现几个问题,其中包括测试错误的内容和在测试和使用之间状态的更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接