How to get ByteArray from Protobuf in Java

10,858 views
Skip to first unread message

mark...@gmail.com

unread,
Jun 4, 2015, 7:34:58 PM6/4/15
to prot...@googlegroups.com
I am new to Protobuf.

Here is my problem


I am using toByteArray() method on a protobuf object in java to get the binary representation of teh object
Then i send the object via web socket to the client
When the client receives the Message, i convert from binary to Protobuf object using parseFrom.

Parsing and Serialization
Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include: 

  • byte[] toByteArray();: serializes the message and returns a byte array containing its raw bytes. 
  • static Person parseFrom(byte[] data);: parses a message from the given byte array. 
  • void writeTo(OutputStream output);: serializes the message and writes it to an OutputStream
  • static Person parseFrom(InputStream input);: reads and parses a message from an InputStream.

The sender only send 9 bytes and receives gets a huge message. Basically the sender and receivers are receiving different size message for the Protobuf object

Is toByteArray() the proper way to generate Byte ARRAY from the Protobuf object? If so, how to parse it on the client side?

Thank you

Mark

Ilia Mirkin

unread,
Jun 5, 2015, 10:40:11 AM6/5/15
to mark...@gmail.com, prot...@googlegroups.com

These are the right steps. Make sure that the sender and receiver see the same data. Should be obvious, but protobuf has no framing, so if you want to send a bunch in one stream, you need to handle that.

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at http://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages