I'm maintaining some Java code that is required to send a
single data packet through a socket. The packet will contain multiple types of data: int, long, raw bytes, and characters.
Currently, the code uses a DataOutputStream that is bound to the socket's output stream, and issues separate packets for each data element. For example:
Code:
m_strm.writeInt(id);
m_strm.writeLong(queueTime);
m_strm.writeLong(sendTime);
m_strm.writeInt(senderID);
m_strm.writeInt(data.length);
m_strm.write(data);
m_strm.writeInt(returnAddress.length());
m_strm.writeChars(returnAddress);
It is my understanding that each statement above issues a separate packet through the socket, and this is not desirable.
How can I write all of the data to a temporary buffer, and then perform a write() of that data? Does Java offer a class that I can use to serialize data similar to the DataOutputStream, but that offers a way to actually get that data in the form of a byte array?
P.S. I've contemplated just defining a Serializable object that holds all of the data that I wish to send, then using an ObjectOutputStream to write the object via the Socket. Is this the best approach to solve this problem?