Question

I am getting a input stream from apache's telnet client.Every time I send a command to telnet client it writes the terminal output back to InputStream,but this stream remains open until the telnet session.

Now I want a way to read the data on this stream till the end.Problem is end can't be determined as the stream is always open.One workaround I found was to read data till a specific character is encountered(which is prompt in most of the cases).but the prompt keeps on changing based on command and I have no way to know what it ll be after command execution.

there is a similar question on SO which explains it better but there is no answer :

Problems with InputStream

Please help...

Was it helpful?

Solution 2

finally I did using timeout.So basically,I did that ,if character is not available for 1 sec then give up.Instead of inputStream.read() I used this :

private char readChar(final InputStream in){
        ExecutorService executor = Executors.newFixedThreadPool(1);
        //set the executor thread working
        Callable<Integer> task = new Callable<Integer>() {
            public Integer call() {
               try {
                   return in.read();
               } catch (Exception e) {
                  //do nothing
               }
               return null;
            }
         };

         Future<Integer> future = executor.submit(task);
         Integer result =null;
         try {
              result= future.get(1, TimeUnit.SECONDS); //timeout of 1 sec
          } catch (TimeoutException ex) {
              //do nothing
          } catch (InterruptedException e) {
             // handle the interrupts
          } catch (ExecutionException e) {
             // handle other exceptions
          } finally {
              future.cancel(false);
              executor.shutdownNow();
           }

         if(result==null)
             return (char) -1;
        return  (char) result.intValue();
    } 

OTHER TIPS

You need to spawn a seperate Thread for reading. You cannot just go in a "Ping-Pong"-manner on one thread for exactly the reason you are faced with.

By the way: The question you linked by now has an accepted answer. It suggests not to drive the CPU to 100% load which is really good advice :)

The read Method however blocks, so you just can put it in a loop into a thread and call back when there is something received. End the loop and terminate the thread on IOException or "-1" and live happily everafter :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top