我们有一个类通过套接字与另一个主机通信,它看起来像这样:
SocketChannel sc = SocketChannel.open(new InetSocketAddress(HOST, PORT));
sc.configureBlocking(true);
...
sc.write(...)
sc.read(...)
这个类工作得很好,除非 HOST 关闭,然后 SocketChannel.open 永远阻塞。我试图通过执行以下操作来使此超时:
SocketChannel = SocketChannel.open();
sc.configureBlocking(false);
boolean result = socketChannel.connect(new InetSocketAddress(HOST, PORT));
if (!result) {
long startTime = System.currentTimeMillis();
while (!socketChannel.finishConnect()) {
if (System.currentTimeMillis() - startTime< 1000) {
// keep trying
Thread.sleep(100);
} else {
// FAILED!
enabled = false;
return;
}
}
}
// SUCCESS!
socketChannel.configureBlocking(true);
enabled = true
好吧,由于某种原因,当我预计它根本不会阻塞时,finishConnect() 会永远阻塞。有任何想法吗?