java StreamCorruptedException:无效类型代码:7704000,ObjectInputStream需要什么?

java StreamCorruptedException:无效类型代码:7704000,ObjectInputStream需要什么?,java,serialization,Java,Serialization,我正在编写一个网络java代码,我似乎无法理解ObjectInputStream解释字节所需的先决条件是什么。 以下是代码的一部分: InputStream is = /* creation of the stream */ ObjectInputStream in = new ObjectInputStream(is); System.out.println(in.readInt()); // the exception is thrown here 异常和堆栈跟踪: java.io.Str

我正在编写一个网络java代码,我似乎无法理解ObjectInputStream解释字节所需的先决条件是什么。 以下是代码的一部分:

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();
有趣的是,当我将“in.readInt()”替换为手动读取的“is”时,当我弹出得到的字节时: -84 -19 0 5 119 4 0 0 0 1 我在谷歌上搜索了序列化协议,它的意思似乎是: “-84-19”->序列化协议幻数 “0 5”->版本 “119”->数据类型(TC_块数据) “01”->我的整数=1

因此,无效类型代码“7704000”是“119 4 0 0”部分的十六进制

此时,我不知道在哪里搜索,ObjectInputStream似乎无法理解协议

输入流是自定义的,下面是其代码的一部分:

@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;
}
@覆盖
public int read()引发IOException{
字节[]字节=新字节[4];
如果(读取(字节,0,4)!=4)
返回-1;
其他的

返回字节[0]Your
read()
方法已损坏。它应该返回一个字节。如果您打算编写自己的实现,您应该彻底阅读InputStream的javadoc。

是的,您是对的,当我意识到ObjectInputStream$BlockDataInputStream.readBlockHeader实现使用read()获取字节时,我正在阅读ObjectInputStream实现。 fact read()返回一个整数,使我将其实现为读取4个字节。。。 我应该更仔细地阅读InputStream的javadoc

感谢您的帮助!

您的第一个read()方法复制了DataInputStream.readInt()。第二个方法是多余的。第三个方法同上。此代码不像您想象的那么神奇。