Search code examples
javaserializable

How to send size of serialized data before the data itself?


I'm crating a client-server chat application. After discovering the C/C++ approach with sending bytes of data is a real pain in Java (signed bytes are simply hilarious), I started trying to use more convenient methods - specifically Serializable interface and ObjectOutputStream along with ByteArrayOutputStream.

This answer quite describes what I know at the moment.

So, I can convert my object into a byte array, which can then be put into output buffer that is eventually sent (the sending is done asynchronously).

Now with object, I need to send the size of the byte array first - so that the receiving function knows how much data should be read before parsing the object.

So in this code:

  out = new ObjectOutputStream(bos);   
  out.writeObject(this);
  return bos.toByteArray();

Can I somehow prepend the object size?

  out = new ObjectOutputStream(bos);   
  out.writeObject(this);
  //PSEUDO FUNCTION - beware
  out.writeIntOnOffset(out.size(), 0) //Push the size on the beginning of the array
  return bos.toByteArray();

Solution

  • Once you have object size just send it:

    MyClass obj = ....;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(obj); // this is what you already have.
    int size = baos.length; // now we have size
    
    OutputStream socketStream = .... // I guess you know how to get it. 
    ObjectOutputStream socketOos = new ObjectOutputStream(socketStream);
    socketOos.writeInt(size);
    socketOos.write(baos.toByteArray());