微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java InputStream.read(byte [],int,int)方法,如何阻塞,直到读取了确切的字节数

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

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

后来我读了这个方法Javadoc:

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

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.

我想知道是否有任何Java“开箱即用”解决方案阻止,直到len字节被读取,如果需要永远等待.

我可以明显地创建一个简单的循环,但我觉得我正在重塑轮子.你可以建议我一个干净的Java感知解决方案吗?

解决方法

使用DataInputStream.readFully.这是 JavaDoc
InputStream in = ...
DataInputStream dis = new DataInputStream( in );
byte[] array = ...

dis.readFully( array );

原文地址:https://www.jb51.cc/java/125693.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐