如何使用同一连接将RMI服务器替换为另一RMI服务器?

时间:2019-10-22 00:22:23

标签: java rmi

我正在一个项目中,我有n个客户端连接到RMI服务器(主RMI服务器)。该服务器连接了另一台服务器,称为备份RMI服务器。当备份服务器发生故障/关闭(例如CTRL + C),成为主RMI服务器时,备份服务器应该承担主RMI服务器的角色。

为了保留客户端与服务器之间的连接而不必再次连接所有内容或再次对服务器进行客户端查找( Naming.lookup ),有一种方法可以转移连接第一台服务器到另一台之间?

我已经尝试在备份服务器上的 LocateRegistry.getRegistry(PORT)中使用 LocateRegistry.createRegistry(PORT).rebind(RMINAME,this)< / strong>时,创建“ RMI连接”(我知道它不是类似于套接字的连接,只是为了使事情保持简单)。没有解决问题,或者至少我不确定它是否被正确使用。

RMI服务器类

try {
// First try to connect to Primary server (the case where this is 
//supposed to be Backup server)
    ci = (RMIInterface) Naming.lookup("RMIConnection");
// This function is what makes the Backup server aware that the Primary
// server failed. It's a while(true) loop with a Thread.sleep(2000)
// that invokes a simple RMI method to test the connection
   checkPrimaryServerStatus();
} 
catch (java.rmi.ConnectException e) {
       System.out.println("No primary RMIServer yet. Connecting...");
} finally {
     // If it isn't backup server, creates connection
         if (!isBackup) {
             try {
              LocateRegistry.createRegistry(RMIPORT).rebind(RMINAME, this);
             } catch (Exception err) {
                 System.out.println("\nERROR: Something went wrong. Aborting program...");
                 err.printStackTrace();
                 System.exit(-1);
             }
        }
}

RMI客户端类

try {
    ci = (RMIInterface) Naming.lookup("RMIConnection");
} catch (java.rmi.ConnectException e) {
    System.out.println("\nConnect the server first.");
    System.exit(-1);
}

这样可以正确创建主服务器和备份服务器,但是,如果主服务器已关闭并且备份接管了用户,则用户将无法像使用主服务器那样与备份进行通信。 问题是将连接从一个“转移”到另一个。

0 个答案:

没有答案