0

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();
Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

2 Answers2

0

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());
AlexR
  • 114,158
  • 16
  • 130
  • 208
-1

You should definitely not mess with the array it self. Instead you should create a separate method that returns size

Shervin Asgari
  • 23,901
  • 30
  • 103
  • 143