几个小时以来,我一直在努力解决 RMI 问题。它现在是一个非常愚蠢的例子,只有当我在同一台计算机上启动客户端和服务器时才有效。一旦我在 != 机器上启动客户端 ^ 服务器,当服务器尝试调用回调时,我会得到一个异常:
Exception creating connection to: 192.168.244.1; nested exception is:
java.net.SocketException: Network is unreachable
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:632)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:128)
顺便说一句,由于我在 10.0.0.x 子网上,这没有任何意义,这个 IP 来自哪里?
该代码由两个类组成,Server 和 Client,实现了两个 {Server|Client} 接口。我从 RMIRegistry 获取服务器对象并调用登录方法没有问题。我可以通过服务器端的断点看到代码已执行,但是一旦涉及回调指令,它就会失败。例外是客户端顺便说一句。
我尝试在两台机器上禁用防火墙,但均未成功。我怀疑问题来自异常发送给我的 ip,但我不知道它来自哪里。
这是以下代码:(Client.java)
public class Client extends UnicastRemoteObject implements ClientInterface {
public static void main(String[] args) {
try {
new Client();
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
public Client() throws RemoteException, MalformedURLException, NotBoundException {
ServerInterface s = null;
s = (ServerInterface) Naming.lookup("rmi://10.0.0.48/server");
s.login(this);
}
@Override
public void talk() throws RemoteException {
System.out.println("Talkiiiing");
}
}
(客户端接口.java)
public interface ClientInterface extends Remote {
void talk() throws RemoteException;;
}
(服务器.java)
public class Server extends UnicastRemoteObject implements ServerInterface {
public Server() throws RemoteException, MalformedURLException {
LocateRegistry.createRegistry(1099);
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
Naming.rebind("rmi://localhost:1099/server", this);
}
public static void main(String[] args) {
try {
new Server();
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
public void login(ClientInterface clientInterface) throws RemoteException {
clientInterface.talk();
}
}
最后是(ServerInterface.java)
public interface ServerInterface extends Remote {
void login(ClientInterface clientInterface) throws RemoteException;
}