繁体   English   中英

从InputStream读取所有字节

[英]Read all byte from InputStream

我想从活动tcp连接的InputStream异步读取所有字节。 输入缓冲区中可能没有任何内容,在这种情况下,我需要一个空字节array []而不是读取/超时。

我尝试了这个:

byte[] bytes = IOUtils.toByteArray(tcpInputStream);

但是,如果InputStream中没有任何内容,则读取将挂起,直到tcp超时,然后引发异常。

您可以使用非阻塞SocketChannel:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

...

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 80));
ByteBuffer buffer = ByteBuffer.allocate(2048);
int bytesRead;
while ((bytesRead = socketChannel.read(buffer)) >= 0) {
    if (bytesRead == 0)
        Thread.sleep(1000); // do usefull stuff
    else {
        // use the bytes and prepare the buffer for next read
        buffer.clear();
    }
}
socketChannel.close();

当服务器关闭连接时,还要准备IOException

暂无
暂无

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

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