问题描述
我正在尝试让RMI程序正常运行。到目前为止,服务器正常启动但客户端无法将远程对象转换为接口。
I'm trying to get a RMI program to work. So far, the server starts up correctly but the client fails casting the remote object to the interface.
我发现的所有其他答案都是针对最终用户使用InterfaceMonitorImpl(客户端未知)而不是Interface的情况。这不是我的情况,我真的在这里亏本 - RMI是噩梦。
All other answers I've found are for cases where the end user has cast the equivalent of InterfaceMonitorImpl (unknown to the client) instead of the Interface instead. This is not my case and I'm really at a loss here — RMI is nightmare-ish.
服务器端
主要:
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:
InterfaceMonitor.java:
public interface InterfaceMonitor extends Remote {
int checkAge() throws RemoteException;
}
InterfaceMonitorImpl.java:
InterfaceMonitorImpl.java:
public class InterfaceMonitorImpl implements InterfaceMonitor {
public InterfaceMonitorImpl() throws RemoteException {
}
@Override
public int counter() throws RemoteException {
return 10;
}
}
客户支持
Client side
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也在客户端。
The InterfaceMonitor.java is also on the client side.
感谢您的时间!
推荐答案
显然您必须拥有两份 InterfaceMonitor:
一个在 MonitorClient
中,其中一个可能类似 MonitorServer。
这使得两个不同的类。不是同一类的两个副本。类名,包,方法声明,继承......都必须相同。
Obviously you must have two copies of InterfaceMonitor:
one in MonitorClient
and one in what may be something like MonitorServer.
That makes two different classes. Not two copies of the same class. The class name, package, method declarations, inheritance, ... all have to be the same.
这篇关于Java RMI代理转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!