我正在尝试理解这段代码
DataInputStream stream =
new DataInputStream(
new ByteArrayInputStream(messageBuffer));
int messageLength = stream.readInt();
char recordType = (char) stream.readByte();
byte padding = stream.readByte();
short numberRecords = stream.readShort();
messageBuffer 被初始化为 new byte[32768],通过 Socket.read() 方法填充。 我不明白的是,一旦 messageLength 被初始化为 stream.readInt(),第二个语句将如何工作,即 recordType?
不会是第一个语句从字节数组的开头读取一个 int 而下一个语句从字节数组的开头读取一个字节吗?它究竟如何知道从哪个点读取字节、整数、短裤等?
最佳答案
来自documentation :
A
ByteArrayInputStream
contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by theread
method.
换句话说,DataInputStream
只是从 ByteArrayInputStream
中读取,而后者会记住字节数组中的当前位置,并在每次读取一些数据时推进它。
关于java - 套接字和数据输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6926823/