我尝试制作一个简单的RMI应用程序,它将两个客户端(Bramka,Monitor)与服务器(Centrala)连接起来,client_1(Bramka)与client_2(Monitor)连接起来。
布拉姆卡.class
public class Bramka extends UnicastRemoteObject implements IBramka{
protected Bramka() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String url = "//localhost:1099/RMI";
try{
ICentrala c = (ICentrala) Naming.lookup(url);
c.getZarejestrowaneBramki();
}catch(Exception e){
System.out.println(e);
}
}
public boolean test() throws RemoteException {
System.out.print("Something from client1");
}
}
中央.class:
public class Centrala extends UnicastRemoteObject implements ICentrala {
protected Centrala() throws RemoteException {
super();
}
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
String url = "//localhost:1099/RMI";
try {
Centrala centrala = new Centrala();
Naming.rebind(url,centrala);
System.out.println("centrala wystartowala");
}catch (Exception e ) {
System.out.println(e);
}
}
public void getZarejestrowaneBramki() throws RemoteException {
System.out.println("Something from server");
}
}
监视器.class
public class Monitor extends UnicastRemoteObject implements IMonitor{
protected Monitor() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
String url = "//localhost:1099/RMI";
try{
ICentrala c = (ICentrala) Naming.lookup(url);
IBramka b = (IBramka) Naming.lookup(url); //error
c.getZarejestrowaneBramki();
b.test();
}catch(Exception e){
System.out.println(e);
}
}
public void koniecznaAktualizacja() throws RemoteException {
}
}
我想做的是从客户端中的Bramka
客户端运行方法test
Monitor
。如果我尝试这样做,我会得到异常:
java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to IBramka
如果我想从Centrala
运行方法,它可以正常工作。一些提示?
ICentrala c = (ICentrala) Naming.lookup(url);
IBramka b = (IBramka)Naming.lookup(url);
这说不通。您正在两次查找相同的 URL,并希望能够将其强制转换为两个不同的远程接口。您需要两个 URL,并且还需要Bramka
将自身绑定到第二个 URL 下的注册表。
另一件没有意义的事情是你的术语。这两个都是服务器。