Java InputStream.read(byte [],int,int)方法,如何阻塞,直到读取了确切的字节数 [英] Java InputStream.read(byte[], int, int) method, how to block until the exact number of bytes has been read

查看:110
本文介绍了Java InputStream.read(byte [],int,int)方法,如何阻塞,直到读取了确切的字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的客户端/服务器网络应用程序,通过TCP套接字发送和接收固定大小消息。

I'm writing a simple client/server network application that sends and receives fixed size messages through a TCP socket.

到目前为止,我一直在使用套接字的 getInputStream() getOutputStream()方法获取流的类然后调用读取(byte [] b,int off,int len) InputStream 类每次读取60个字节(这是消息的大小)。

So far, I've been using the getInputStream() and getOutputStream() methods of the Socket class to get the streams and then call the read(byte[] b, int off, int len) method of the InputStream class to read 60 bytes each time (which is the size of a message).

稍后,我读了Javadoc方法:

Later on, I read the Javadoc for that method:


public int read(byte [] b,
int off,
int len)
抛出IOException

public int read(byte[] b, int off, int len) throws IOException

将输入流中最多 len个字节的数据读入
字节的数组。尝试读取len个字节,,但可以读取更小的
数字
。实际读取的字节数以
整数形式返回。

Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.

我想知道是否有任何Javaout-of -the-box阻止直到 len 字节的解决方案,必要时永远等待。

I was wondering if there's any Java "out-of-the-box" solution to block until len bytes have been read, waiting forever if necessary.

我显然可以创建一个简单的循环但是我觉得我正在重新发明轮子。你能建议我一个干净且支持Java的解决方案吗?

I can obviously create a simple loop but I feel like I'm reinventing the wheel. Can you suggest me a clean and Java-aware solution?

推荐答案

使用DataInputStream.readFully。这是 JavaDoc

Use DataInputStream.readFully. Here is JavaDoc

InputStream in = ...
DataInputStream dis = new DataInputStream( in );
byte[] array = ...

dis.readFully( array );

这篇关于Java InputStream.read(byte [],int,int)方法,如何阻塞,直到读取了确切的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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