今天看人家java网络编程源码的时候,看到readInt函数。由于自己对java不是很熟悉,虽然从函数字面意思大概知道函数的用法,还是进一步查阅了java api文档。下面内容是从java api文档中摘抄的:
readInt
public final int readInt() throws IOException
-
See the general contract of the
readInt
method ofDataInput
.Bytes for this operation are read from the contained input stream.
-
-
Returns:
-
the next four bytes of this input stream, interpreted as an
int
.
Throws:
-
EOFException
- if this input stream reaches the end before reading four bytes. -
IOException
- the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
See Also:
-
FilterInputStream.in
-
the next four bytes of this input stream, interpreted as an
注意标红的部分,该函数的意思就是从输入流中读取四个字节。在网络编程中,经常需要构造自己的包结构,最简单的就是用最开始的4bit存储后续data部分的长度。这样在java网络编程中,首先就可以利用readInt函数来读取data部分的长度,然后在利用recv函数循环接受数据内容时,利用该长度值作为判断条件,从而正确接收网络数据。