Java RMI 代理转换问题

标签 java rmi

我正在尝试让 RMI 程序运行。到目前为止,服务器启动正确,但客户端无法将远程对象转换到接口(interface)。

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to MonitorClient.InterfaceMonitor

我发现的所有其他答案都是针对最终用户已转换为 InterfaceMonitorImpl 的等效项(客户端未知)而不是 Interface 的情况。这不是我的情况,我真的很茫然——RMI 简直就是噩梦。

服务器端

主要:

    InterfaceMonitor obj;
    try {
        LocateRegistry.createRegistry(1099);

        InterfaceMonitor stub = (InterfaceMonitor) UnicastRemoteObject.exportObject(new InterfaceMonitorImpl(), 0);

        Registry registry = LocateRegistry.getRegistry();
        registry.bind("imon", stub);

        System.out.println("Server ready");
    } catch (RemoteException | AlreadyBoundException ex) {
        System.out.println("Server error: " + ex.toString());
    }

InterfaceMonitor.java:

public interface InterfaceMonitor extends Remote {
    int checkAge() throws RemoteException; 
}

InterfaceMonitorImpl.java:

public class InterfaceMonitorImpl implements InterfaceMonitor {

    public InterfaceMonitorImpl() throws RemoteException {

    }

    @Override
    public int counter() throws RemoteException {
        return 10;
    }

}

客户端

    try {
        Registry reg = LocateRegistry.getRegistry(null);
        InterfaceMonitor im = (InterfaceMonitor) reg.lookup("imon");

        int counter = im.counter();
        System.out.println("Counter: " + counter);
    } catch (NotBoundException | RemoteException ex) {
        Logger.getLogger(MonitorGUI.class.getName()).log(Level.SEVERE, null, ex);
    }

InterfaceMonitor.java 也在客户端。

感谢您的宝贵时间!

最佳答案

显然,您必须拥有两份 InterfaceMonitor 副本: 一份位于 MonitorClient 中,另一份可能位于 MonitorServer 之类的位置。 这使得两个不同的副本类。不是同一类的两个副本。类名、包、方法声明、继承……都必须相同。

关于Java RMI 代理转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23804625/

相关文章:

java.rmi.ConnectException : Connection refused to host: 127. 0.0.1

java - 从 Java 应用程序访问 Windows API - JNI 或 JNA?

java - 如何在具有多个标签的嵌入式 Neo4j 中获取节点?

java - 从自定义函数读取文件是 FC 应用程序

java - 如何用 Java RMI 实现观察者模式?

java - 我正在运行 RMI 应用程序但没有安全管理器 : RMI class loader disabled exception comes

java - Controller 和远程工作机器之间的连接

Java 远程接口(interface)阻止使用我的 GUI

java - 解析 SMTP 中的实际电子邮件地址

Java Jpanel 仅在完成代码后更新