Tempo limite de conexão ao soquete usando o NIO SocketChannel [duplicado]
Esta questão já tem uma resposta aqui:
Especifique o tempo limite de conexão em java.nio 2 respostasNós temos uma classe que está falando com outro HOST em um soquete e se parece com isso:
SocketChannel sc = SocketChannel.open(new InetSocketAddress(HOST, PORT));
sc.configureBlocking(true);
...
sc.write(...)
sc.read(...)
Essa classe funciona muito bem, exceto se o HOST estiver inativo e o SocketChannel.open for bloqueado para sempre. Eu tentei fazer esse tempo limite fazendo o seguinte:
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
Bem, por algum motivo, o finishConnect () está bloqueando para sempre quando eu esperava que ele não bloqueasse. Alguma ideia?