For my multiplayer game, I'm trying to figure out a system to send multiple pieces of data from one client to another and separating pieces of data.

When sending a message, all parameter data has to be converted into a byte array (with BitConverter.GetBytes) and will arrive as such on the other side.

What I'm not sure about is how to send multiple numbers in one message and identify them. For example, how would I send a ushort and a ulong in a single byte array? Are there any clever methods to identify the individual numbers or will every number have to be packaged in 4 bytes each?

  • \$\begingroup\$ You will need some protocol or formatting that both ends can understand. TLV is quite popular, for instance. \$\endgroup\$ – glampert Feb 2 '15 at 4:42
  • \$\begingroup\$ Oh, thanks for that info. I've implemented a similar system based on the TLV. \$\endgroup\$ – JPtheK9 Feb 2 '15 at 4:49

Int32, Int16, Int16, Int32, Int32, Int32

If your app wrote these numbers in this order, then you just read them in the same order. It is your game and you just know the format you are sending and read it the same way you wrote it.

If you want to be able to change the format (e.g. send Int8 for a small map and Int16 for a big one) you define a key that tells you the upcoming format. E.g.:

is_small_map, Int32, Int8, Int8, Int32, Int32, Int32

is_big_map, Int32, Int16, Int16, Int32, Int32, Int32

When you need to pass arrays - write elements count first and then write/read them in a loop.

When you need to pass multiple packets over net, one after another you just pass them, letting the receiver side to decode the packets individually. For that each packet needs to include it's Length, so when you decode it you know exactly where this packet ends and next one starts.

  • \$\begingroup\$ Wow, that's a lot more efficient than my system! By ordering them, I could use just a 6 byte wrapper. Thanks! \$\endgroup\$ – JPtheK9 Feb 2 '15 at 5:15
  • \$\begingroup\$ Knowing the elements order is a great "win" for many algorithms out there. Take advantage of it! \$\endgroup\$ – Kromster says support Monica Feb 2 '15 at 5:24
  • \$\begingroup\$ Embarrassingly, I actually read your answer wrong (byte arrays can be of varying sizes) and inserted my own idea but the concept is still the same - supply as much information as you can client side. I plan to order the data types from smallest to largest and have a byte to identify the lengths of each section. \$\endgroup\$ – JPtheK9 Feb 2 '15 at 5:27

I was brainstorming something like that where the first 5 bytes in my array will define the lengths of all my numbers (types won't be needed; they're all integral numbers). The first 4 bytes identifies the byte length of every following number.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.