我正在编写一个简单的客户端/服务器网络应用程序,通过TCP套接字发送和接收固定大小的消息.
到目前为止,我一直在使用Socket类的getInputStream()和getOutputStream()方法来获取流,然后调用InputStream类的read(byte [] b,int off,int len)方法来读取60每个字节(这是消息的大小).
public int read(byte[] b,
int off,
int len)
throws IOExceptionReads 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 );