I have a java server that has to communicate over a TCP socket to an external program written in C. They pass messages back and forth in a message protocol that can't be changed (due to reasons too complicated to go into here).
The TCP messaging protocol looks roughly like this:
Header (with message length) -> Message body -> Message CRC
It seems to me like this is best handled on the java side with an ObjectInputStream/ObjectOutputStream pair and classes that implement java.io.Serializable and have their own writeObject() and readObject() methods. The problem is that the only solution I can think of for implementing this messaging protocol involves an extra level of indirection that I want to avoid if at all possible.
The diffculty is the write portion of the socket and comes because the message length is in front of the message body. My current solution is to write the message body to a secondary ObjectOutputStream (for the sole purpose of knowing the message length), then writing the header (with length) to the socket, followed by the body then the CRC.
My question is this: is there a better way to do this than to use the temporary ObjectOutputStream? That seems pretty wasteful.
Thanks.