What is the best way to send information messages like: position, healt to server and then broadcast them to all the players (how to "pack" and "unpack" them in a good and fast way?)
i have a message system that manages structs (messages) like:
struct position{
long entityId;
float x;
float y;
float z;
};
and now, i need to "pack" this structs (i can change this structs to any other suggestion) in a fast way to send them to the server (through the network) and then "unpack" them in the client side.
I'm interested in how mmo game's do that.
Thanks!
Variable types that may make use of a FPU and may contain a different memory representation [not only byte order] on different architectures (such as float
and double
) should never be used in network transfers if the architecture of both ends cannot be known (or, in other words, is not granted to be a specific architecture).
A float
type representation may conform to IEEE 754 specification in one architecture, but it's not granted that every architecture complies to it. Always make use of types whose sizes are well-known (such as uint16_t
, uint32_t
, etc. from stdint.h
) and make use of htons()
/ ntohs()
/ htonl()
/ ntohl()
(from arpa/inet.h
) to convert from host byte order to network byte order and vice-versa.
You'll also need to make use of compiler extensions to grant alignments (such as __attribute__ ((align()))
, or #pragma pack()
) to grant that the structure alignment is the same on both ends.
If you don't want [or cannot make use of] compiler extensions (due to portability issues), then structs are not the [direct] way to go.
In that case, you can still use structures in your code, but you should implement custom serialization / unserialization routines in order to build a buffer to be transmitted (also accounting for host to network and network to host byte order and never making use of float
/ double
types [FPU] unless you cover these conversions in you serialization routines).
Also, take a look at this question, and read all the answers from it with positive vote rating (I only have to add to it that you should only use stdint.h
types when dealing with network communications).