Vince Yau
Vince Yau

Reputation: 555

Java InputStream throwing java.io.StreamCorruptedException

I have a problem that I do not quite understand. I have a server socket and a client socket on two separate machines. Server will constantly sends out data in hex and connected client will read the data stream and do some work. Most of the traffic is happening in that manner. On a few rare occasions, client will send a bytestring to Server. At this point, I am getting Java.io.StreamCorruptedException at this line:

 ObjectInputStream in = new 
    ObjectInputStream(socketFromClient.getInputStream());

Exception:

   java.io.StreamCorruptedException: invalid stream header: 020001B5
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
    at ReadInput.run(ReadInput.java:21)
    at java.lang.Thread.run(Thread.java:745)

"020001B5" is exactly the bytestring that client is sending over to server.

I do not understand why I am getting this StreamCorruptedException. My code logic does not have any "stream header". What is stream header? I checked javadoc and I could not make out of why this is happening.

Any tip much appreciated.

thanks

-v

Upvotes: 0

Views: 152

Answers (1)

ck1
ck1

Reputation: 5443

Your client is not writing data using ObjectOutputStream: that's why you're seeing this exception. ObjectOutputStream and ObjectInputStream are used for serializing and deserializing Java objects.

Instead of using ObjectInputStream to read data, consider using BufferedReader or a DataInputStream.

See this example for more details.

Upvotes: 1

Related Questions