Search code examples
javaobjectinputstream

How to resolve StreamCorruptedException: invalid stream header in java?


I get this exception while trying to send objects over UDP socket in java

java.io.StreamCorruptedException: invalid stream header: 00000000

Here is the code for sender: `

public class Epl_Client implements Serializable{
public static void main(String[] args )
{
 try{
  ParseMessage pm = new PaseMessage();  
  DatagramSocket Sock;
  Sock = new DatagramSocket();
  DatagramPacket Dp;
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(4 * 1024);
  ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  objectOutputStream.writeObject(lg);
  byte[] objectBytes = byteArrayOutputStream.toByteArray();
  Dp = new DatagramPacket(objectBytes,   objectBytes.length,InetAddress.getByName("localhost"),9876);

  Sock.send(Dp);

    Sock.close();

 }
 catch (Exception e){
 System.out.println("exception caught" + e);
 }
}}

Code for receiver :

public class ClassServer{
public static void main(String[] args){
    ParseMessage pm=new ParseMessage();

    try{         
        byte[] recvBuf = new byte[5000];
        while(true){ 
                DatagramSocket serverSocket = new DatagramSocket(9876);
               ByteArrayInputStream bais = new ByteArrayInputStream(recvBuf);
               ObjectInputStream objectInputStream = new ObjectInputStream(bais);
               pm= (ParseMessage)objectInputStream.readObject();
               System.out.println(pm.message);
               bais.close();
               objectOutputStream.close();
              }
        }
        catch(Exception e)
        {
            System.out.println("Exceptiom"+e);
        }  
}}

And the class

public class ParseMessage  implements Serializable{
  String message; 
  public ParseMessage() 
 { message="Inavalid";}}

Can anyone help to resolve this error?


Solution

  • You're never actually receiving anything from the socket. Look at your code - you create a DatagramSocket and then never refer to it again. You're always building a ByteArrayInputStream wrapping an array full of zeroes.

    You need to call DatagramSocket.receive, and then use the length of the received data when constructing a ByteArrayInputStream. However, you'll need to be certain that you can fit all the data in a single packet. Are you sure you don't want a stream-based protocol?