套接字和数据输入流
我试图理解这段代码
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 被初始化为新字节[32768],通过 Socket.read() 方法填充。 我不明白的是,一旦 messageLength 被初始化为stream.readInt(),第二条语句将如何工作,即recordType?
第一个语句不会从字节数组的开头读取一个 int ,而下一个语句不会从字节数组的开头读取一个字节吗?它到底如何知道从哪个点读取字节、整数、短整型等?
I am trying to understand this snippet of code
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 is initialised as new byte[32768] as is populated via a Socket.read() method.
What i dont understand is once messageLength has been initialised to stream.readInt(), how will the second second statement work i.e. recordType?
Wouldnt the first statement read an int from the beginning of the byte array and the next statement read a byte from the beginning of the byte array? How exactly does it know from which point to read the bytes, ints, shorts etc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自文档:
换句话说,
DataInputStream
只是从ByteArrayInputStream
读取,而后者记住字节数组中的当前位置,并在每次读取某些数据时前进。From the documentation:
In other words,
DataInputStream
simply reads from theByteArrayInputStream
, while the latter remembers the current position in the byte array and advances it every time some data has been read.readX()
不会从流的开头读取。事实上,术语流用于表示随着时间的推移而可用的数据序列。这意味着从流中的后续读取将检索不同的元素。将流视为信息传送带而不是数组。
readX()
doesn't read from the beginning of the stream. In fact the term stream is used to denote a sequence of data made available over time. That means subsequent reads from a stream will retrieve different elements.Think of a stream as a conveyor belt of information rather than an array.
DataInputStream.read*
方法消耗底层输入流中的字节。在这种情况下,read* 方法读取 ByteArrayInputStream 提供的下一个可用字节,该字节将跟踪数组中的当前位置。作为旁注,您可能需要考虑使用 ByteBuffer.wrap 和各种 ByteBuffer.read 方法:
The
DataInputStream.read*
methods consume bytes from the underlying input stream. In this case theread*
methods read the next available bytes provided by theByteArrayInputStream
which will keep track of the current position in the array.As a side-note, you may want to consider using
ByteBuffer.wrap
and the variousByteBuffer.read
methods:Socket.read() 将读取可用的字节。最小为一字节!最大值是缓冲区大小,其中可以包含任意数量的消息。
使用 DataInputStream/BufferedInputStream 比手动读取缓冲区更安全、更简单、更高效。
Socket.read() will read the bytes which are available. The minimum is one byte! The maximum is the buffer size which could have any number of messages in it.
Instead of reading a buffer manually, it is safer, simpler and more efficient to use a DataInputStream/BufferedInputStream.