Aegis2D
Modular C++26 2D game engine for networked games
Loading...
Searching...
No Matches
aegis2d::net Namespace Reference

Binary serialization, UDP/TCP sockets and the network thread. More...

Classes

class  AckTracker
 Receiver side of the acknowledgements: which datagrams of the peer arrived. More...
 
class  BinaryReader
 Reads values written by BinaryWriter from untrusted bytes, never past their end. More...
 
class  BinaryWriter
 Writes values field by field into a growing byte buffer. More...
 
class  BitReader
 Reads values written by BitWriter from untrusted bytes, never past their end. More...
 
class  BitWriter
 Writes values of any width from 0 to 64 bits into a growing byte buffer. More...
 
class  Endpoint
 IPv4 or IPv6 address and port of a peer. More...
 
class  NetworkContext
 Runs the completion of network operations: received datagrams, finished sends. More...
 
class  NetworkThread
 Runs a NetworkContext on a thread of its own, until stopped. More...
 
struct  PacketHeader
 Header at the start of every UDP datagram. More...
 
struct  ReliabilitySettings
 Settings of a ReliableChannel. More...
 
class  ReliableChannel
 Sequences, acknowledgements and reliable events of the datagrams exchanged with one peer. More...
 
class  RttEstimator
 Smoothed round trip time and its variation, from round trip samples. More...
 
class  SocketError
 Thrown when a socket cannot be opened or bound. More...
 
class  TcpConnection
 TCP connection exchanging whole messages over the byte stream. More...
 
class  TcpListener
 Listening TCP socket handing every accepted peer over as a TcpConnection. More...
 
struct  TrafficCount
 A number of datagrams and the bytes they hold. More...
 
class  TrafficCounters
 Counts the datagrams exchanged with one peer, by direction and packet type. More...
 
class  UdpSocket
 UDP socket bound to a local endpoint, receiving and sending whole datagrams. More...
 

Enumerations

enum class  PacketType : std::uint8_t {
  Connect = 1 , Accept = 2 , Input = 3 , Snapshot = 4 ,
  Event = 5 , Heartbeat = 6 , Disconnect = 7
}
 What a datagram carries; stored on one byte after the version. More...
 
enum class  HeaderError : std::uint8_t { Truncated , BadMagic , BadVersion , UnknownType }
 Why read_header() rejected a datagram. More...
 
enum class  TcpCloseReason : std::uint8_t { PeerClosed , Error , MessageTooLarge }
 Why a TcpConnection closed by itself. More...
 
enum class  Direction : std::uint8_t { Sent = 0 , Received = 1 }
 Way a datagram went. More...
 

Functions

std::optional< std::vector< std::byte > > compress_payload (std::span< const std::byte > payload)
 Compresses a payload with LZ4.
 
std::optional< std::vector< std::byte > > decompress_payload (std::span< const std::byte > compressed)
 Decompresses a payload written by compress_payload().
 
void write_datagram (BinaryWriter &writer, PacketHeader header, std::span< const std::byte > payload, std::optional< std::size_t > threshold=std::nullopt)
 Writes a datagram: its header, then its payload, compressed when that pays.
 
std::optional< std::vector< std::byte > > read_payload (const PacketHeader &header, BinaryReader &reader)
 Reads the payload of a datagram, decompressed if its header says it is compressed.
 
std::string_view name () noexcept
 Name of the module, used to check that it is linked.
 
std::string_view to_string (PacketType type) noexcept
 Name of a packet type, for logs.
 
std::string_view to_string (HeaderError error) noexcept
 Short description of a header error, for logs.
 
void write_header (BinaryWriter &writer, const PacketHeader &header)
 Writes the 18-byte header, magic and version included.
 
std::variant< PacketHeader, HeaderError > read_header (BinaryReader &reader) noexcept
 Reads and checks the header at the start of a datagram.
 
constexpr bool sequence_greater_than (std::uint16_t a, std::uint16_t b) noexcept
 Whether sequence a was sent after sequence b, the counter having possibly wrapped in between.
 
constexpr bool sequence_less_than (std::uint16_t a, std::uint16_t b) noexcept
 Whether sequence a was sent before sequence b, the counter having possibly wrapped in between.
 

Variables

constexpr std::size_t default_compression_threshold = 128
 Default size from which write_datagram() tries to compress a payload, in bytes.
 
constexpr std::size_t max_datagram_size = 1200
 Largest UDP datagram the protocol sends or accepts, header included.
 
constexpr std::size_t max_events_in_flight = 256
 Largest number of events sent and not yet acknowledged at once.
 
constexpr std::size_t max_event_size = PacketHeader::max_payload_size - 1 - 2 - 2
 Largest event, in bytes: one alone fills an Event datagram.
 
constexpr std::uint16_t sequence_half_range = 32768
 Half the range of a 16-bit sequence: the largest gap at which two sequences are still ordered is one less.
 
constexpr std::size_t max_message_size = 4096
 Largest message a TcpConnection sends or accepts, in bytes, prefix excluded.
 
constexpr std::size_t message_prefix_size = 2
 Size of the length prefix in front of each message: a little-endian u16.
 

Detailed Description

Binary serialization, UDP/TCP sockets and the network thread.

Enumeration Type Documentation

◆ Direction

enum class aegis2d::net::Direction : std::uint8_t
strong

Way a datagram went.

Enumerator
Sent 

Sent to the peer.

Received 

Received from the peer.

◆ HeaderError

enum class aegis2d::net::HeaderError : std::uint8_t
strong

Why read_header() rejected a datagram.

Enumerator
Truncated 

Fewer than PacketHeader::size bytes.

BadMagic 

The first four bytes are not PacketHeader::magic: not our protocol.

BadVersion 

Another protocol version.

UnknownType 

The type byte, its compressed flag aside, is not a PacketType.

◆ PacketType

enum class aegis2d::net::PacketType : std::uint8_t
strong

What a datagram carries; stored on one byte after the version.

The values are part of the protocol: never renumber them, and keep them contiguous (read_header() checks the range).

Enumerator
Connect 

Client to server: binds the client's UDP endpoint to its session.

Accept 

Server to client: the endpoint is bound, gameplay traffic may start.

Input 

Client to server: the player's input state for one tick.

Snapshot 

Server to client: the state of the world.

Event 

Both ways: gameplay events that must arrive (spawn, death...), resent until acknowledged.

Heartbeat 

Both ways: keeps the session alive and carries acknowledgements when there is nothing else to send.

Disconnect 

Both ways: the sender leaves the session.

◆ TcpCloseReason

enum class aegis2d::net::TcpCloseReason : std::uint8_t
strong

Why a TcpConnection closed by itself.

Enumerator
PeerClosed 

The peer closed its side of the connection.

Error 

The connection failed: reset by the peer, unreachable, failed send...

MessageTooLarge 

The peer announced a message larger than max_message_size.

Function Documentation

◆ compress_payload()

std::optional< std::vector< std::byte > > aegis2d::net::compress_payload ( std::span< const std::byte >  payload)

Compresses a payload with LZ4.

Parameters
payloadPayload to compress, at most PacketHeader::max_payload_size bytes.
Returns
The size of payload (u16) then its LZ4 block, or std::nullopt if payload is empty, too large, or does not come out smaller.

◆ decompress_payload()

std::optional< std::vector< std::byte > > aegis2d::net::decompress_payload ( std::span< const std::byte >  compressed)

Decompresses a payload written by compress_payload().

Parameters
compressedBytes after the header of a datagram whose header is compressed.
Returns
The original payload, or std::nullopt if compressed is malformed: shorter than 2 bytes, a size of 0 or above PacketHeader::max_payload_size, or an LZ4 block that is invalid or does not give exactly that size.

◆ name()

std::string_view aegis2d::net::name ( )
noexcept

Name of the module, used to check that it is linked.

Returns
"net", a view of a static string.

◆ read_header()

std::variant< PacketHeader, HeaderError > aegis2d::net::read_header ( BinaryReader &  reader)
noexcept

Reads and checks the header at the start of a datagram.

Checks, in this order, that the 18 bytes are there, the magic, the version and the type. A rejected datagram must be dropped without reading further.

Parameters
readerReader at the start of the datagram; on success, it is left at the payload.
Returns
The header, or the reason the datagram is rejected.

◆ read_payload()

std::optional< std::vector< std::byte > > aegis2d::net::read_payload ( const PacketHeader &  header,
BinaryReader &  reader 
)

Reads the payload of a datagram, decompressed if its header says it is compressed.

Parameters
headerHeader of the datagram, from read_header().
readerReader left at the payload by read_header(); on success, it is at the end.
Returns
The payload, or std::nullopt if it is compressed and malformed (see decompress_payload()); the reader then does not move.

◆ sequence_greater_than()

constexpr bool aegis2d::net::sequence_greater_than ( std::uint16_t  a,
std::uint16_t  b 
)
constexprnoexcept

Whether sequence a was sent after sequence b, the counter having possibly wrapped in between.

a is more recent when it is ahead of b by 1 to 32767 steps, counting from 65535 back to 0: 0 is more recent than 65535, and 10 than 40000. Two sequences exactly 32768 apart are not ordered: neither is more recent than the other.

Parameters
aSequence to test.
bSequence it is compared with.
Returns
true if a is more recent than b; false if they are equal, if b is more recent, or if they are 32768 apart.

◆ sequence_less_than()

constexpr bool aegis2d::net::sequence_less_than ( std::uint16_t  a,
std::uint16_t  b 
)
constexprnoexcept

Whether sequence a was sent before sequence b, the counter having possibly wrapped in between.

Parameters
aSequence to test.
bSequence it is compared with.
Returns
true if b is more recent than a, see sequence_greater_than().

◆ to_string() [1/2]

std::string_view aegis2d::net::to_string ( HeaderError  error)
noexcept

Short description of a header error, for logs.

Parameters
errorError to describe.
Returns
"truncated header", "bad magic", "bad version" or "unknown type".

◆ to_string() [2/2]

std::string_view aegis2d::net::to_string ( PacketType  type)
noexcept

Name of a packet type, for logs.

Parameters
typeType to name.
Returns
"Connect", "Accept"... or "unknown" for a value outside the enum.

◆ write_datagram()

void aegis2d::net::write_datagram ( BinaryWriter &  writer,
PacketHeader  header,
std::span< const std::byte >  payload,
std::optional< std::size_t >  threshold = std::nullopt 
)

Writes a datagram: its header, then its payload, compressed when that pays.

The payload is compressed when threshold is given, the payload holds at least that many bytes, and compress_payload() makes it smaller; the header written then has PacketHeader::compressed set, whatever header says.

Parameters
writerWriter of the datagram, empty.
headerHeader of the datagram.
payloadPayload of its type.
thresholdSize from which to try compressing; std::nullopt never compresses.

◆ write_header()

void aegis2d::net::write_header ( BinaryWriter &  writer,
const PacketHeader &  header 
)

Writes the 18-byte header, magic and version included.

Parameters
writerWriter of the datagram; the payload follows the header.
headerFields to write.

Variable Documentation

◆ default_compression_threshold

constexpr std::size_t aegis2d::net::default_compression_threshold = 128
inlineconstexpr

Default size from which write_datagram() tries to compress a payload, in bytes.

Below it, LZ4 rarely saves more than the 2 bytes of the size it adds.

◆ max_datagram_size

constexpr std::size_t aegis2d::net::max_datagram_size = 1200
inlineconstexpr

Largest UDP datagram the protocol sends or accepts, header included.

Below common path MTUs, so datagrams are never fragmented by IP.

◆ max_event_size

constexpr std::size_t aegis2d::net::max_event_size = PacketHeader::max_payload_size - 1 - 2 - 2
inlineconstexpr

Largest event, in bytes: one alone fills an Event datagram.

The payload of a datagram minus the event count (u8) and the id and length of the event (u16 each).

◆ max_events_in_flight

constexpr std::size_t aegis2d::net::max_events_in_flight = 256
inlineconstexpr

Largest number of events sent and not yet acknowledged at once.

ReliableChannel::send() refuses more. Bounding them lets the receiver detect duplicates with a window of this many event ids (RFC section 5.3).

◆ max_message_size

constexpr std::size_t aegis2d::net::max_message_size = 4096
inlineconstexpr

Largest message a TcpConnection sends or accepts, in bytes, prefix excluded.

TCP only carries the session (login), so messages stay small; a peer announcing a larger one is closed before anything is allocated.

◆ message_prefix_size

constexpr std::size_t aegis2d::net::message_prefix_size = 2
inlineconstexpr

Size of the length prefix in front of each message: a little-endian u16.

◆ sequence_half_range

constexpr std::uint16_t aegis2d::net::sequence_half_range = 32768
inlineconstexpr

Half the range of a 16-bit sequence: the largest gap at which two sequences are still ordered is one less.