title: Java TelnetClient InputStream closed after open
body: <p>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.</p>
  
  <pre><code>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 &lt;= 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;
    }
  </code></pre>
  
  <p>If I leave out the <code>Thread.sleep(500)</code> it will never have any availableBytes. With the pause, it has a result of 20, however, if I try to use <code>isInput.read()</code> it will return -1 which means the InputStream is closed.</p>
  
  <p>I'm looking for a way to catch connection failures and try the connection again. It happens too frequently to not try again.</p>