简体   繁体   English

在非阻塞模式下从InputStream读取所有字节

[英]Read all bytes from InputStream in non blocking mode

Trying to find solution to read all bytes from InputStream in non blocking mode. 试图找到在非阻塞模式下从InputStream读取所有字节的解决方案。 Section inputStream.read() in function below blocks forever when no data are available. 当没有可用数据时,下面函数中的inputStream.read()节将永远阻止。

private static String extract(InputStream inputStream) throws IOException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();               
    byte[] buffer = new byte[1024];
    int read = 0;
    while ((read = inputStream.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, read);
    }       
    baos.flush();       
    return  new String(baos.toByteArray(), "UTF-8");
}

How to read all bytes without blocking? 如何不阻塞地读取所有字节?

I assume you want a timeout for reading. 我假设您想超时阅读。

For an URLConnection (should the InputStream stem from that) you can set miscellaneous timeouts, and check the optimal blocksize (that from the sender). 对于URLConnection(InputStream应该源于此),您可以设置其他超时,并检查最佳块大小(来自发送者)。

For Sockets the same functionality exists. 对于套接字,存在相同的功能。

A timeout one can make oneself using a thread: this I found on SO . 超时可以使自己使用线程: 这是我在SO上发现的

But also Future seems appropriate: Future似乎也很合适:

ExecutorService service = Executors.newFixedThreadPool(2); // Or whatever.
// Callable<String> callable = () -> extract(inputStream);
Future<String> future = service.submit(() -> extract(inputStream));
try {
    String s = future.get(3, TimeUnit.SECONDS);
} catch (Exception e){
    e.printStackTrace();
    future.cancel(true);
    inputStream.close();
}

您可以使用InputStream.available()方法在读取之前测试多少字节可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM