0

我从 apache 的 telnet 客户端获取输入流。每次我向 telnet 客户端发送命令时,它都会将终端输出写回 InputStream,但此流在 telnet 会话之前保持打开状态。

现在我想要一种方法来读取该流上的数据直到结束。由于流始终处于打开状态,因此无法确定问题是否结束。我发现的一种解决方法是读取数据直到遇到特定字符(在大多数情况下)。但是提示会根据命令不断变化,我无法知道命令执行后会是什么。

SO上有一个类似的问题可以更好地解释它,但没有答案:

InputStream 的问题

请帮忙...

4

2 回答 2

0

您需要生成一个单独的线程来阅读。出于您所面临的原因,您不能只是在一个线程上以“乒乓”方式进行。

顺便说一句:你现在链接的问题有一个公认的答案。它建议不要将 CPU 驱动到 100% 负载,这是一个非常好的建议 :)

然而,该read方法会阻塞,因此您只需将其放入线程中的循环中,并在收到某些内容时回调。结束循环并在 IOException 或“-1”上终止线程并从此过上幸福的生活:)

于 2012-10-30T10:12:15.870 回答
0

最后我确实使用了超时。所以基本上,我这样做了,如果字符在 1 秒内不可用,然后放弃。而不是 inputStream.read() 我使用了这个:

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();
    } 
于 2012-10-31T10:51:17.653 回答