R-Type  2
Doom but in better
Loading...
Searching...
No Matches
ProtocolHandler.cpp
Go to the documentation of this file.
1/*
2** EPITECH PROJECT, 2024
3** ProtocolHandler.cpp
4** File description:
5** Handle message format Sent/received to/from the server
6*/
7
14
15GUI::Network::Packet::Packet(MessageType type, const std::vector<uint8_t> &payload)
16 : type(type), size(static_cast<uint16_t>(payload.size())), payload(payload)
17{
18}
19
24
26{
27 return size;
28}
29
30const std::vector<uint8_t> &GUI::Network::Packet::getPayload() const
31{
32 return payload;
33}
34
35std::vector<uint8_t> GUI::Network::Packet::serialize(const GUI::Network::Packet &packet)
36{
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());
42
43 return buffer;
44}
45
47{
48 if (data.size() < 3)
49 throw std::runtime_error("Invalid packet size");
50
51 MessageType type = static_cast<MessageType>(data[0]);
52 uint16_t size = (static_cast<uint16_t>(data[1]) << 8) | static_cast<uint16_t>(data[2]);
53
54 if (data.size() - 3 != size)
55 throw std::runtime_error("Payload size mismatch");
56
57 std::vector<uint8_t> payload(data.begin() + 3, data.end());
58
59 return Packet(type, payload);
60}
61
62const std::string GUI::Network::Packet::print() const
63{
64 std::string result = "";
65 result += "Packet Type: " + Recoded::myToString(static_cast<int>(type)) + "\n";
66 result += "Packet Size: " + Recoded::myToString(size) + "\n";
67 result += "Payload: ";
68 for (auto byte : payload) {
69 result += Recoded::myToString(static_cast<int>(byte)) + " ";
70 }
71 result += "\n";
72 return result;
73}
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.
Definition Rect.hpp:223