16 : type(type), size(static_cast<uint16_t>(payload.size())), payload(payload)
37 std::vector<uint8_t> buffer;
38 buffer.push_back(
static_cast<uint8_t
>(packet.type));
39 buffer.push_back(
static_cast<uint8_t
>((packet.size >> 8) & 0xFF));
40 buffer.push_back(
static_cast<uint8_t
>(packet.size & 0xFF));
41 buffer.insert(buffer.end(), packet.payload.begin(), packet.payload.end());
49 throw std::runtime_error(
"Invalid packet size");
52 uint16_t size = (
static_cast<uint16_t
>(data[1]) << 8) |
static_cast<uint16_t
>(data[2]);
54 if (data.size() - 3 != size)
55 throw std::runtime_error(
"Payload size mismatch");
57 std::vector<uint8_t> payload(data.begin() + 3, data.end());
59 return Packet(type, payload);
64 std::string result =
"";
67 result +=
"Payload: ";
68 for (
auto byte : payload) {
This file defines the Packet class responsible for serializing and deserializing a custom binary UDP ...
Represents a packet for the custom binary UDP protocol.
const std::string print() const
Prints a string representation of the packet's contents, for debugging purposes.
uint16_t getSize() const
Gets the size of the packet's payload.
MessageType getType() const
Gets the message type of the packet.
static std::vector< uint8_t > serialize(const Packet &packet)
Serializes a Packet object into a vector of bytes suitable for network transmission.
static Packet deserialize(const std::vector< uint8_t > &data)
Deserializes a packet from a vector of bytes received over the network.
Packet(MessageType type=MessageType::P_ERROR, const std::vector< uint8_t > &payload={})
Constructs a Packet with a specified message type and payload.
const std::vector< uint8_t > & getPayload() const
Gets the payload of the packet.
MessageType
Enum for the different message types in the UDP protocol.
const std::string myToString(const Rect< RectType > &rectangle)
Converts a Rect<T> object to its string representation.