如何在不阻塞的情况下从 Java 中的 BufferedReader 读取? [英] How can I read from a BufferedReader in Java without blocking?

查看:38
本文介绍了如何在不阻塞的情况下从 Java 中的 BufferedReader 读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向服务器发送命令,然后查看是否收到响应.

I want to send a command to a server, and find out if I get a response.

现在我正在使用 BufferedReaderreadline() 函数,该函数会阻塞直到服务器响应,但我要做的就是验证是否存在首先来自服务器的响应.

Right now i am using BufferedReader's readline() function, which blocks until there's a response from server, but all I want to do is verify that there's a response from the server in the first place.

我尝试使用 ready()reset() 来避免这个块,但它没有帮助.

I tried using ready() or reset() to avoid this block, but it doesn't help.

这导致我的程序在等待服务器响应时卡住,这从未发生过.InputStreamReader 似乎在做同样的事情,根据我的理解.

This is causing my program to get stuck waiting for the server to respond, which never happens. InputStreamReader seems to do the same thing, by my understanding of things.

我在这里找到的关于该主题的其他问题没有回答我的问题,所以如果你能回答我的问题,那就太好了.

Other questions I found here on the subject didn't answer my question, so please if you can answer my question it will be great.

推荐答案

您可能只需要 InputStream 而无需将其包装在 BufferedReader

May be all you need is the InputStream without wrapping it in a BufferedReader

while (inputStream.available() > 0) {
     int i = inputStream.read(tmp, 0, 1024);
     if (i < 0)
          break;
     strBuff.append(new String(tmp, 0, i));
}

我希望这会有所帮助.

这篇关于如何在不阻塞的情况下从 Java 中的 BufferedReader 读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆