I need to aggregate 2 Strings and a List into a single byte[] in order to send it through the network (using a special library that has a function send(byte[]).
Then, on the other end, I need to get the 3 different objects back.
I’ve done an ugly implementation of it, but it is very slow. Basically, what I do is
public byte[] myserializer(String dataA, String dataB, List<byte[]> info) {
byte[] header = (dataA +";" + dataB + ";").getBytes();
int numOfBytes = 0;
for (byte[] bs : info) {
numOfBytes += bs.length;
}
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o;
try {
o = new ObjectOutputStream(b);
o.writeObject(info);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = b.toByteArray();
int length = header.length + data.length;
byte[] headerLength = (new Integer(header.length)).toString()
.getBytes();
byte[] pattern = ";".getBytes();
int finalLength = headerLength.length + pattern.length + length;
byte[] total = new byte[finalLength];enter code here
total = // Copy headerLength, header and total into byte[] total
return return;
In essence I’m creating kind of a frame that looks like this
HEADER INFO
(———————————————–)(———————————-)
HEADER_LENGHT;DATA_A;DATA_B;SERIALIZED_LIST_OBJECT
Then, on the receiver side, I do the inverse process and that’s “all”. This works, but it is PRETTY inefficient and ugly.
Suggestions? Best practices? Ideas?
Oh…just one note more: this have to work for J2SE and Android too
Thanks so much in advanced!!
Here is a simplistic method of serializing an array of bytes and deserialize it on the other side. Note that the method only accept one argument of type
List<byte[]>and since your argumentdataAanddataBare of typeString, you can simply assume that the two firstbyte[]elements in the list are those two argument. I believe that this is a lot faster than object serialization through anObjectOutputStreamand will be faster to deserialize on the other side as well.The frame is constructed as
The example above will output
Note that the frame format is formed of
byte[]chunks so as long as you know the order of the chunks, you can use these methods with virtually any set of data.