0
\$\begingroup\$

I am working on a project that is sending data from pc to tablet via usb, using android adb. To serialize the data, we are using BinaryFormatter. The problem I'm running into is that the client is sending packets of size 1161 bytes.

Now I could hard code in 1161 as the length of the byte array on the receiving in, and this would fix my problem. But what I would rather do is put the length in the header of the packet being sent, so the receiving end can check that and create the packet according to the size, just incase we get a different packet type of a different size.

However, BinaryFormatter also encodes the names of the fields, so as far as I can tell, you can't determine the length the object will be before serializing it, at which point, it's too late to set the length property in the header.

Does any one know a solution to this that will elegantly handle different packet sizes, and packets over the size of 1024 bytes? Thank you!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I've slightly modified your title to not assume the only solution is to determine the length before serialization. In some similar situations, I've seen code reserve some bytes at a known location in the buffer to put the size, then perform the serialization and measure the actual size, then seek back and overwrite the reserved bytes with the now-known size. It's also possible that BinaryFormatter itself records this information somewhere we can access. I don't know for sure whether either route is applicable here, but it's usually best to ask about the root problem and keep the door open. \$\endgroup\$
    – DMGregory
    Oct 15 '20 at 13:10
  • \$\begingroup\$ Thanks for the assist! \$\endgroup\$ Oct 15 '20 at 13:16
  • \$\begingroup\$ You may also want to consider using a different serialization strategy. BinaryFormatter stores a lot of plaintext data that both ends of the communication should already have, bloating the bandwidth required to send it around and it is not safe to use on untrusted data being sent to you by a third party - like from a client (or agent claiming to be one) over a network. You may find alternatives that are leaner, faster, more secure, and length-prefixed. \$\endgroup\$
    – DMGregory
    Oct 15 '20 at 13:22
  • \$\begingroup\$ @DMGregory so I'm pretty new to networking things but, I don't believe any of that will be a problem. This is being sent via usb to an android tablet. And it will always be only from one Unity project to another Unity project, both specifically developed for this or something similar... and always developed in house by our team. \$\endgroup\$ Oct 15 '20 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.