0

I'm trying to load an object via ObjectOutputStream using sockets.

I'm testing on the same machine.

I receive this error:

java.io.StreamCorruptedException: invalid type code: 00
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
    at java.io.ObjectInputStream.readSerialData(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readArray(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
    at java.io.ObjectInputStream.readSerialData(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)

I use this code to create the ObjectOutputStream:

InputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(in);
Object readObject = objectInputStream.readObject();

The more strange is that there is no probleam when I pass objects that are not so big.

The size in bytes of the object I read that returns probleam is about: 73423 bytes.

I pass a java.util.Vector via ObjectOutputStream.

If I pass an amount greater than 5 it throws the above exception.

I also created a simple test (without passing through a socket) to ensure the Object is Serializable, it works without problems. NNTraining is the class I'm serializing:

    Vector<NNTraining> nn = new Vector<NNTraining>();
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream o = new ObjectOutputStream(b);
    o.writeObject(nn);
    o.close();
    ByteArrayInputStream bb = new ByteArrayInputStream(b.toByteArray());
    ObjectInputStream oo = new ObjectInputStream(bb);
    Vector<NNTraining> v2 = (Vector<NNTraining>) oo.readObject();
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
felipe
  • 1,212
  • 1
  • 15
  • 27

1 Answers1

0

You don't need all this mucking around with byte arrays and ByteArrayInputStreams. Just attach the ObjectInputStream directly to the socket,once, and call readObject() every time you want to. At the sender, attach the ObjectOutputStream directly to the socket, once, and call writeObject() every time you need to.

The problem you're getting is because you aren't doing this.

user207421
  • 305,947
  • 44
  • 307
  • 483