Apache Commons TelnetClientを使用して、一部のスイッチの自動Telnetインターフェイスを作成しています。マシンから直接スイッチにtelnetで接続すると、接続がタイムアウトしないように見えます。ランダムに、Javaプログラムでは、接続はInputStreamとともにすぐに閉じるように見えます。接続の失敗を確認して再接続を試みるチェックを作成しようとしましたが、最初に失敗した場合は常に失敗します。
import org.apache.commons.net.telnet.TelnetClient;
public String connect()
{
String errorMessage = null;
tcConnectionHandle = new TelnetClient();
tcConnectionHandle.setDefaultTimeout(iTimeOutMilliseconds);
try
{
tcConnectionHandle.connect(strConnectionIP, intConnectionPort);
osOutput = tcConnectionHandle.getOutputStream();
isInput = tcConnectionHandle.getInputStream();
int availableBytes = isInput.available();
while(availableBytes <= 0)
{
tcConnectionHandle = null;
isInput = null;
osOutput = null;
Thread.sleep(500);
tcConnectionHandle = new TelnetClient();
Thread.sleep(500);
tcConnectionHandle.setDefaultTimeout(iTimeOutMilliseconds);
Thread.sleep(500);
tcConnectionHandle.connect(strConnectionIP, intConnectionPort);
Thread.sleep(500);
osOutput = tcConnectionHandle.getOutputStream();
Thread.sleep(500);
isInput = tcConnectionHandle.getInputStream();
Thread.sleep(500);
availableBytes = isInput.available();
System.out.println("reopened: " + availableBytes);
}
}
catch(InterruptedException iX)
{
errorMessage = "Could not establish connection. " + iX.getLocalizedMessage();
}
catch(SocketException sX)
{
errorMessage = sX.getMessage();
}
catch(IOException ioX)
{
errorMessage = ioX.getMessage();
}
return errorMessage;
}
省略した場合Thread.sleep(500)
、availableBytesはありません。一時停止すると、結果は20になりますが、使用しようとするisInput.read()
と-1が返されます。これは、InputStreamが閉じていることを意味します。
接続障害をキャッチして接続を再試行する方法を探しています。頻繁に発生するため、再試行できません。