I am using Apache Commons TelnetClient to make an automated telnet interface for some switches. If I telnet to the switch directly from the machine, the connection never seems to time out. Randomly, in the Java program, the connection seems to close immediately along with the InputStream. I was trying to build a check that sees the connection failure and tries to make the connection again, but if it fails the first time, it always fails.
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;
}
If I leave out the Thread.sleep(500) it will never have any availableBytes. With the pause, it has a result of 20, however, if I try to use isInput.read() it will return -1 which means the InputStream is closed.
I’m looking for a way to catch connection failures and try the connection again. It happens too frequently to not try again.
I think the InputStream attached to the TelnetClient was randomly in a closed state. Any attempts to read it while in that state made communication fail even if I created a new TelnetClient Object and reconnected to the same Telnet server later. It doesn’t make sense, but I decided to try a new approach instead of figuring out what was happening in the TelnetClient class.
I solved the issue by using
implements TelnetInputListenerfor this class. InputStream is occasionally null whentelnetInputAvailable()is called, but I am able to recover from it now by not doing anything on that particular call to the function.