UDP provides message based communication however it is not connection oriented nor does it have any built in functionality for reliable or fragmented delivery of messages hence the implementation to cover this if fairly complicated.
The UDP protocol has multiple layers of header data depending on the send options that are requested with the message.
All header data in Hazel is encoded in big endian format.
In both of these,
Type is an identifier
that holds the SendOption or another value indicating a control
packet of data. The most significant 4 bits of
Type are reserved for future use and the
least significant bits specify the send option flags for the message.
Fragmented are both flags for their
respective send option,
Control, if set,
specifies that the 3 least significant bits refer to a control code:
To implement reliable delivery 2 ID bytes are sent which identify the packet. When the receiver receives the data is replys with an acknowledgement packet as follows:
Where type is specifying an acknowledgement packet as laid out above.
If the sending client does not receive an acknowledgement after a specific amount of time elapses from the pakcet being sent then it resends that packet and thetime before the next resend of that packet is doubled. When the sending client receives the acknowledgement is should not resend the data again.
The receiving client must also ensure that it does not present the same packet to the user twice but must acknowledge any packets it receives, even if it has already received that packet, in case an acknowledgement is lost.
After a specific number of resends without acknowledgement a sending client may mark assume that communication has been interrupted and thus mark the connection as disconnected.
Keepalive packets should be sent after a specific time has elapsed since the last packet (either keepalive, acknowledgement or user sent) was transmitted and should be sent using reliable delivery so that an acknowledgement can be received to indicate communication has not been lost. As packets that are not acknowledged should cause a disconnection no additional logic is required for keepalives.