gale.net.protocol module

This file contains the wire-level constants and helpers shared by every piece of gale.net: the channel identifiers, the packet header format, and the sequence number comparison used by the reliability layer.

Author: Alejandro Mujica (aledrums@gmail.com)

class gale.net.protocol.Channel[source]

Bases: object

Identifies how a message should be delivered.

  • UNRELIABLE: sent once, may be lost or arrive out of order. Use it for data that is superseded by the next update anyway, such as a position snapshot sent every frame.

  • RELIABLE_ORDERED: guaranteed to arrive, and to be delivered to on_message callbacks in the same order it was sent. Use it for events where both matter, such as a chat log.

  • RELIABLE_UNORDERED: guaranteed to arrive, but may be delivered out of order. Cheaper than RELIABLE_ORDERED since it never has to hold a packet back waiting for an earlier one. Use it for events that must not be lost but are independent of each other, such as “a point was scored”.

UNRELIABLE: int = 0
RELIABLE_ORDERED: int = 1
RELIABLE_UNORDERED: int = 2
gale.net.protocol.is_sequence_newer(a, b)[source]

Compare two 32-bit sequence numbers that wrap around, accounting for the wraparound: after the highest representable sequence number comes 0 again, so a plain a > b comparison would be wrong close to that wraparound point.

Parameters:
  • a (int) – A sequence number.

  • b (int) – A sequence number to compare against.

Returns:

Whether a is newer than b, assuming neither is more than half the sequence space ahead of the other (the standard assumption for this technique).

Return type:

bool

gale.net.protocol.pack_header(channel, token, sequence, ack, ack_bitfield)[source]
Parameters:
  • channel (int) – One of the Channel constants.

  • token (int) – The connection token for this peer.

  • sequence (int) – This packet’s sequence number (per channel, per direction).

  • ack (int) – The last sequence number received from the peer on this channel.

  • ack_bitfield (int) – Bit i (0-indexed) set means sequence number (ack - 1 - i) was also received.

Returns:

The packed header bytes.

Return type:

bytes

gale.net.protocol.unpack_header(data)[source]
Parameters:

data (bytes) – Raw packet bytes, at least HEADER_SIZE long.

Returns:

A tuple (channel, token, sequence, ack, ack_bitfield).

Raises:

struct.error – If data is shorter than HEADER_SIZE.