Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8456601
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T12:35:08+00:00 2026-06-10T12:35:08+00:00

I am using Apache Commons TelnetClient to make an automated telnet interface for some

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T12:35:10+00:00Added an answer on June 10, 2026 at 12:35 pm

    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 TelnetInputListener for this class. InputStream is occasionally null when telnetInputAvailable() is called, but I am able to recover from it now by not doing anything on that particular call to the function.

    public String connect()
    {
       String errorMessage = null;
       tcConnectionHandle = new TelnetClient();
       tcConnectionHandle.setDefaultTimeout(iTimeOutMilliseconds);
       tcConnectionHandle.registerInputListener(this);
    
       try
       {
          tcConnectionHandle.connect(strConnectionIP, intConnectionPort);
          osOutput = tcConnectionHandle.getOutputStream();
          isInput = tcConnectionHandle.getInputStream();
       }
       catch(SocketException sX)
       {
          errorMessage = sX.getMessage();
       }
       catch(IOException ioX)
       {
          errorMessage = ioX.getMessage();
       }
    
       return errorMessage;
    }
    
    public Matcher waitForRegularExpression(String regularExpression)
    {
       Matcher matcher;
       Pattern pattern = Pattern.compile("(?s)" + regularExpression);
       StringBuilder warningLog = new StringBuilder();
    
       synchronized(sbInputBuffer)
       {
          matcher = pattern.matcher(sbInputBuffer.toString());
    
          while(!matcher.find())
          {
             try
             {
                int inputBufferSize = sbInputBuffer.length();
                sbInputBuffer.wait(iTimeOutMilliseconds);
    
                if(inputBufferSize == sbInputBuffer.length())
                {
                   warningLog.append("Did not find pattern and no new input.");
                   logWarning(warningLog.toString());
                   return null;
                }
             }
             catch(InterruptedException intX)
             {
                warningLog.append("Interrupted waiting on input. ").append(intX.getLocalizedMessage());
             }
    
             matcher = pattern.matcher(sbInputBuffer.toString());
          }
    
          sbInputBuffer.delete(0, matcher.end()-1);
       }
    
       if(!warningLog.toString().isEmpty())
       {
          logWarning(warningLog.toString());
       }
    
       return matcher;
    }
    
    @Override
    public void telnetInputAvailable()
    {
       synchronized(sbInputBuffer)
       {
          StringBuilder warningLog = new StringBuilder();
          int readBytes = -2;
    
          if(isInput != null)
          {
             try
             {
                readBytes = isInput.read();
    
                if(readBytes > 0)
                {
                   sbInputBuffer.append((char)readBytes);
                }
    
                sbInputBuffer.notify();
             }
             catch(IOException ioX)
             {
                warningLog.append("Failed for IO: ").append(ioX.getLocalizedMessage()).append(" - input so far: ")
                   .append(sbInputBuffer.toString()).append("\nRead bytes: ").append(readBytes).append("\n");
                logWarning(warningLog.toString());
             }
          }
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using apache.commons.net.telnet . I have char[] array . I am calling TelnetClient.getOutputStream().write(array[i]).
I'm using Apache Commons HttpClient to grab some data from a server. My problem
I am using apache commons-net for downloading a file from an FTP server. That
I'm using Apache Commons to make my HTTP calls, and in my activity I
I'm using Apache Commons VFS (Virtual File System) to access some files over SFTP.
I am using Apache Commons HttpClient 3.1, and I found that HttpURLConnection from Sun
I'm using the Apache Commons Configuration. How can I get directly a String of
I am using Apache Commons Email to send out the emails from our web
I'm using Apache Commons' FTPClient to talk to an FTP server and upload some
I am using Spring 2.5; a SimpleJdbcTemplate using apache-commons-dbcp connection pooling. There is also

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.