Java 套接字和数据输入流
我试图理解这段代码Java 套接字和数据输入流,java,sockets,datainputstream,Java,Sockets,Datainputstream,我试图理解这段代码 DataInputStream stream = new DataInputStream( new ByteArrayInputStream(messageBuffer)); int messageLength = stream.readInt(); char recordType = (char) stream.readByte();
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,下一条语句不从字节数组的开头读取字节吗?它如何确切地知道从哪个点读取字节、整数、短字符等 来自:
ByteArrayInputStream
包含包含字节的内部缓冲区
可以从流中读取的内部计数器跟踪
read
方法提供的下一个字节。
换句话说,
DataInputStream
只是从ByteArrayInputStream
读取,而后者记住字节数组中的当前位置,并在每次读取一些数据时将其向前推进。DataInputStream.read*
方法消耗底层输入流中的字节。在这种情况下,read*
方法读取ByteArrayInputStream
提供的下一个可用字节,该字节将跟踪数组中的当前位置
作为一个旁注,您可能需要考虑使用<代码> ByteBuffer。包装< /代码>和各种<代码> ByteBuffer。
ByteBuffer msgBuf = ByteBuffer.wrap(messageBuffer);
int messageLength = msgBuf.getInt();
char recordType = msgBuf.getChar();
...
readX()
不从流的开头读取。事实上,流一词用于表示一段时间内可用的数据序列。这意味着从流中后续读取将检索不同的元素
将流视为信息的传送带,而不是数组。Socket.read()将读取可用的字节。最小值是一个字节!最大值是缓冲区大小,其中可以包含任意数量的消息
使用DataInputStream/BufferedInputStream比手动读取缓冲区更安全、更简单、更高效
// create an input stream once per socket.
DataInputStream stream =
new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
int messageLength = stream.readInt();
char recordType = (char) stream.readByte();
byte padding = stream.readByte();
short numberRecords = stream.readShort();
谢谢我在看文档,看的是DataInputStream。谢谢。我正在看的代码是非常旧的代码,我怀疑我是否能够修改它。