在让 RMI 服务器在多宿主计算机上正常工作时,我遇到了一些障碍。我写了一个自定义RMISocketFactory
我尝试实现客户端 createSocket(String host, int port)
方法有几种不同的方法。一种方法仅在 RMI 服务器计算机为多宿主时才有效,另一种方法仅在 RMI 服务器计算机不是多宿主时才有效。这是我的代码 createSocket
我的客户端中的方法版本 RMISocketFactory
实现:
仅当 RMI 服务器不是多宿主时才有效:
@Override
public Socket createSocket(String host, int port) throws IOException{
Socket s = new Socket(host,port);
//Do some book-keeping here ...
return s;
}
仅当 RMI 服务器是多宿主时才有效:
private TreeSet<String> validHosts = null;
@Override
public Socket createSocket(String host, int port) throws IOException{
Socket s = null;
try {
s = new Socket(host,port);
synchronized(this){
if(validHosts == null) validHosts = new TreeSet<String>();
validHosts.add(host);
}
} catch (IOException e) {}
if(s == null && validHosts != null){
synchronized(this){
for(String h : validHosts){
try {
s = new Socket(h,port);
} catch (IOException e) {}
}
}
}
if(s == null){
try {
String h = RemoteServer.getClientHost();
s = new Socket(RemoteServer.getClientHost(),port);
synchronized(this){
if(validHosts == null) validHosts = new TreeSet<String>();
validHosts.add(h);
}
} catch (Exception e) {}
}
//No dice - throw an exception:
if(s == null){
TreeSet<String> set = new TreeSet<String>();
set.add(host+"(orig)");
synchronized(this){
if(validHosts != null) set.addAll(validHosts);
}
StringBuilder sb = new StringBuilder(
"Could not connect socket on port "+port+
" to any of the following hosts: ");
for(String h : set) sb.append(h+" ");
throw new IOException(sb.toString());
}
//Do some book-keeping here ...
return s;
}
问题
看起来,如果我能以某种方式判断服务器端计算机是否是多宿主的,那么我可以将两组代码包装在 if(serverIsMultihomed) ... else ...
中。一种声明。我确实能够在此调用中获取服务器的实际计算机名称,但调用 InetAddress.getAllByHostName(host)
实际上并不返回主机的所有 IP 地址,仅返回客户端计算机上的 NIC 可见的 IP 地址。那么当 createSocket(host,port)
被调用的 IP 地址实际上对客户端不可见,这就是我遇到问题的地方。此外,设置 java.server.rmi.hostname
到我想要使用的服务器的 IP 地址并不能解决此问题,并且本质上会禁止服务器所连接的不同子网上的计算机建立链接。
缺点是,是否有另一种方法可以从不同的机器获取主机的所有 IP 地址(可见或其他),或者我在这里完全找错了树?
最佳答案
你看过this Multihomed solution吗? ?
关于java - 有没有办法确定远程 RMI 服务器计算机是否是多宿主的,即使它的某些 IP 地址不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10520413/