readInt函数的使用

来源:互联网 发布:c语言开发实战宝典 编辑:程序博客网 时间:2024/05/23 18:10

今天看人家java网络编程源码的时候,看到readInt函数。由于自己对java不是很熟悉,虽然从函数字面意思大概知道函数的用法,还是进一步查阅了java api文档。下面内容是从java api文档中摘抄的:

readInt

public final int readInt()                  throws IOException
See the general contract of the readInt method of DataInput.

Bytes for this operation are read from the contained input stream.

Specified by:
readInt in interface DataInput
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

注意标红的部分,该函数的意思就是从输入流中读取四个字节。在网络编程中,经常需要构造自己的包结构,最简单的就是用最开始的4bit存储后续data部分的长度。这样在java网络编程中,首先就可以利用readInt函数来读取data部分的长度,然后在利用recv函数循环接受数据内容时,利用该长度值作为判断条件,从而正确接收网络数据。

0 0
原创粉丝点击