Java RMI - RegistryImpl_Stub无法强制转换为我的远程接口

时间:2017-10-27 22:58:24

标签: java registry rmi classcastexception stub

我正在使用rmi开发服务器 - 客户端程序。我有2个Rmi的服务器:Primary和BacI尝试访问在另一台机器上运行的RmiServer。在我第一次尝试在两台不同的机器上将客户端连接到rmi时,它开始工作正常,但是在修改了类的方法中的一些内容之后,我就无法将客户端连接到服务器了。我将向您展示服务器和客户端代码的摘录。

服务器端

public class RmiServer extends UnicastRemoteObject implements ConnectionRMI

//MAIN Function

try{
    if(args.length!=4){
        System.out.println("Number of arguments invalid! Rmi Server will close.");
        return;
       }
        address = InetAddress.getByName(args[0]);
        portUdp = Integer.parseInt(args[1]);
        otherPort = Integer.parseInt(args[2]);
        otherAddress = InetAddress.getByName(args[3]);
        Registry registry = LocateRegistry.getRegistry(otherAddress.getHostAddress(), 1099);
                registry.lookup("RmiServer1");
                System.out.println("[INFO]: Backup Server RMI is ready! ");
                primary = false;
            } catch (NotBoundException | RemoteException ex) {
                primary = true;
                try {
                    Registry registry = LocateRegistry.createRegistry(1099);
                    registry.rebind("RmiServer1", registry);
                } catch (RemoteException ex1) {
                    System.out.println("The registry in port 1099 is already created. The program will close\n");
                    return;
                }
                System.out.println("[INFO]: Primary Server RMI is ready! ");

            } catch (UnknownHostException ex) {
                Logger.getLogger(RmiServer.class.getName()).log(Level.SEVERE, null, ex);
            }

接口ConnectionRMI

public interface ConnectionRMI extends Remote{
}

客户端

try{
            address1 = InetAddress.getByName(args[2]);
            address2 = InetAddress.getByName(args[3]);
            registry = LocateRegistry.getRegistry(address1.getHostAddress(), 1099);
            atualRmi = (ConnectionRMI) registry.lookup("RmiServer1");
            server1 = true;
        }

错误在这一行:

atualRmi = (ConnectionRMI) registry.lookup("RmiServer1");

错误:

Exception in thread "main" java.lang.ClassCastException: sun.rmi.registry.RegistryImpl_Stub cannot be cast to sdeleicoes.ConnectionRMI

1 个答案:

答案 0 :(得分:0)

registry.bind("RmiServer1", registry);

问题出在这里。您正在将Registry绑定到自身。这毫无意义。你应该绑定一个远程对象。