简体   繁体   English

检查RMI连接的更好方法

[英]Better way to check for RMI connectivity

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. 下面是一个静态方法,用于检查另一端RMI服务器是否在线,我基本上调用一种方法,如果它回复为true,则表示连接已打开,如果它没有回复,而是给出异常,则表示出现了问题。 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;

}

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. 它容易出现几个问题,其中包括测试错误的东西以及测试和使用之间的状态变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM