mal-packet-weaver
C++20 packet serialization/deserialization library.
Loading...
Searching...
No Matches
session.inl
Go to the documentation of this file.
1#pragma once
2#include "session.hpp"
3
4namespace mal_packet_weaver
5{
6
7 template <IsPacket T>
8 bool Session::send_packet(const T &packet_arg) requires std::is_base_of_v<Packet, T>
9 {
10 if (!alive_)
11 {
12 spdlog::warn("Session is closed, cannot send packet");
13 return false;
14 }
15 spdlog::trace("Encrypting packet {}", packet_arg.packet_name());
16 const auto &packet = static_cast<const Packet &>(packet_arg);
17 ByteArray buffer = ByteArray{ uint32_to_bytes(packet.type) };
18 packet.serialize_to_bytearray(buffer);
19 if (encryption_)
20 {
21 buffer = encryption_->encrypt(buffer);
22 }
23 // byte to check if connection is secured or not.
24 buffer.insert(buffer.begin(), encryption_ ? std::byte{ 1 } : std::byte{ 0 });
25 ByteArray *value = new ByteArray{ std::move(buffer) };
26 spdlog::trace("Encrypted packet {}", packet_arg.packet_name());
27 while (alive_)
28 {
29 if (packets_to_send_.push(value))
30 {
31 spdlog::trace("Pushing packet {}", packet_arg.packet_name());
32 value = nullptr;
33 break;
34 }
35 std::this_thread::yield();
36 }
37 if (!alive_ || value != nullptr)
38 {
39 delete value;
40 return false;
41 }
42 return true;
43 }
44
45} // namespace mal_packet_weaver
Base class for all packets.
Definition packet.hpp:47
bool send_packet(const T &packet_arg)
Sends any packet derived from DerivedPacket through the network.
Definition session.inl:8
This is the main namespace for the Mal Packet Weaver library.
Definition common.hpp:42
ByteArray uint32_to_bytes(const uint32_t value)
Convert a uint32_t value to a ByteArray using little-endian byte order.
A dynamically resizable array of bytes.