问题描述
我正在处理网络 java 代码,我似乎无法理解 ObjectInputStream 需要解释字节的先决条件是什么.这是代码的一部分:
i'm working on a network java code, and i can't seem to understand what are the prerequisites an ObjectInputStream needs to interpret bytes.Here is a part of the code :
InputStream is = /* creation of the stream */
ObjectInputStream in = new ObjectInputStream(is);
System.out.println(in.readInt()); // the exception is thrown here
异常和堆栈跟踪:
java.io.StreamCorruptedException: invalid type code: 77040000
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.read(Unknown Source)
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
发送代码:
OutputStream os = /* creation of output stream */
out = new ObjectOutputStream(os);
out.writeInt(1);
out.flush();
现在是有趣的部分,当我用手动读取is"替换in.readInt()"时,当我读取得到的字节时:-84 -19 0 5 119 4 0 0 0 1我用谷歌搜索序列化协议,它似乎意味着:"-84 -19" -> 序列化协议幻数0 5"-> 版本"119" -> 数据类型 (TC_BLOCKDATA)"0 0 0 1" -> 我的整数 = 1
now the interesting part, when i replace "in.readInt()" with a manual reading of "is", when i pring the bytes i got :-84 -19 0 5 119 4 0 0 0 1i googled serialization protocols and it seems to mean : "-84 -19" -> serialization protocol magic numbers "0 5" -> version "119" -> type of data (TC_BLOCKDATA) "0 0 0 1" -> my integer = 1
因此,无效类型代码77040000"是119 4 0 0"部分的十六进制.
so, the invalid type code "77040000" is the hexadecimal for the "119 4 0 0" part.
此时,我不知道去哪里搜索,ObjectInputStream 似乎无法理解协议.
at this point, i don't know where to search, the ObjectInputStream seems to not be able to understand the protocol.
输入流是自定义的,这里是它的一部分代码:
the input stream is custom, here is part of its code:
@Override
public int read() throws IOException {
byte[] bytes = new byte[4];
if(read(bytes, 0, 4) != 4)
return -1;
else
return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, available());
}
@Override
public int read(byte[] b, int off, int len) throws IOException{
int i;
for(i = 0; i < len; i++){
if(!isReady())
return i == 0 ? -1 : i;
b[i+off] = data[offset++];
}
return i;
}
@Override
public int available() throws IOException {
if(isReady())
return length - offset;
else
return -1;
}
推荐答案
您的 read()
方法已损坏.它应该返回一个字节.如果您打算编写自己的实现,则应仔细阅读 InputStream 的 javadoc.
Your read()
method is broken. It is supposed to return a single byte. You should read the javadoc for InputStream thoroughly if you intend to write your own implementation.
这篇关于java StreamCorruptedException:无效类型代码:77040000,ObjectInputStream 期望什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!