My problem is when it tries to read the object the second time, it throws the exception:
java.io.StreamCorruptedException: invalid type code: AC
at java
The underlying problem is that you are using a new ObjectOutputStream
to write to a stream that you have already used a prior ObjectOutputStream
to write to. These streams have headers which are written and read by the respective constructors, so if you create another ObjectOutputStream
you will write a new header, which starts with - guess what? - 0xAC,
and the existing ObjectInputStream
isn't expecting another header at this point so it barfs.
In the Java Forums thread cited by @trashgod, I should have left out the part about 'anew for each object at both ends': that's just wasteful. Use a single OOS and OIS for the life of the socket, and don't use any other streams on the socket.
If you want to forget what you've written, use ObjectOutputStream.reset().
And don't use any other streams or Readers
or Writers
on the same socket. The object stream APIs can handle all Java primitive datatypes and all Serializable
classes.