Air-Trap 1.0.0
A multiplayer R-Type clone game engine built with C++23 and ECS architecture
Loading...
Searching...
No Matches
Session.cpp
Go to the documentation of this file.
1
9#include "RType/Logger.hpp"
10
11namespace rtp::net
12{
14 // Public API
16
17 Session::Session(uint32_t id,
18 asio::ip::tcp::socket socket,
19 asio::ip::udp::socket& serverUdpSocket,
20 IEventPublisher &publisher)
21 : _id(id),
22 _socket(std::move(socket)),
23 _serverUdpSocket(serverUdpSocket),
24 _publisher(publisher),
25 _timer(_socket.get_executor())
26 {
27 }
28
30 stop();
31 }
32
34 asio::co_spawn(_socket.get_executor(),
35 [self = shared_from_this()] { return self->reader(); },
36 asio::detached);
37
38 asio::co_spawn(_socket.get_executor(),
39 [self = shared_from_this()] { return self->writer(); },
40 asio::detached);
41 }
42
44 if (!_stopped) {
45 _stopped = true;
46 _socket.close();
47 _timer.cancel();
48 }
49 }
50
51 void Session::send(const Packet& packet, NetworkMode mode) {
52 if (mode == NetworkMode::TCP) {
53 std::lock_guard<std::mutex> lock(_writeMutex);
54 _writeQueue.push_back(packet);
55 _timer.cancel();
56 }
57 else if (mode == NetworkMode::UDP && _hasUdp) {
58 auto pkt = std::make_shared<Packet>(packet);
59 auto buffers = pkt->getBufferSequence();
60 _serverUdpSocket.async_send_to(buffers, _udpEndpoint,
61 [](const asio::error_code&, std::size_t){});
62 }
63 }
64
65 void Session::setId(uint32_t id) {
66 _id = id;
67 }
68
69 uint32_t Session::getId() const {
70 return _id;
71 }
72
73 asio::ip::tcp::endpoint Session::getTcpEndpoint() const {
74 return _socket.remote_endpoint();
75 }
76
77 void Session::setUdpEndpoint(const asio::ip::udp::endpoint& endpoint) {
78 _udpEndpoint = endpoint;
79 _hasUdp = true;
80 }
81
83 // Private API
85
86 asio::awaitable<void> Session::reader() {
87 try {
88 while (!_stopped) {
89 Header header;
90 co_await asio::async_read(_socket, asio::buffer(&header, sizeof(Header)), asio::use_awaitable);
91
92 header.magic = Packet::from_network(header.magic);
94 header.bodySize = Packet::from_network(header.bodySize);
95 header.ackId = Packet::from_network(header.ackId);
97
98 if (header.magic != MAGIC_NUMBER) break;
99
100 Packet packet;
101 packet.header = header;
102
103 if (header.bodySize > 0) {
104 packet.body.resize(header.bodySize);
105 co_await asio::async_read(_socket, asio::buffer(packet.body), asio::use_awaitable);
106 }
107
108 _publisher.publishEvent({_id, packet});
109 }
110 } catch (std::exception&) {
111 stop();
113 }
114 }
115
116 asio::awaitable<void> Session::writer() {
117 try {
118 while (!_stopped) {
119 if (_writeQueue.empty()) {
120 asio::error_code ec;
121 _timer.expires_at(std::chrono::steady_clock::time_point::max());
122 co_await _timer.async_wait(redirect_error(asio::use_awaitable, ec));
123 } else {
124 Packet packet;
125 {
126 std::lock_guard<std::mutex> lock(_writeMutex);
127 packet = _writeQueue.front();
128 _writeQueue.pop_front();
129 }
130 co_await asio::async_write(_socket, packet.getBufferSequence(), asio::use_awaitable);
131 }
132 }
133 } catch (std::exception&) {
134 stop();
135 }
136 }
137
138} // namespace rtp::net
Logger declaration with support for multiple log levels.
Interface for network event handling.
virtual void publishEvent(NetworkEvent event)=0
Get buffer sequence for network transmission.
Network packet with header and serializable body.
Definition Packet.hpp:471
BufferSequence getBufferSequence(void) const
Get buffer sequence for network transmission.
Definition Packet.cpp:36
std::vector< uint8_t > body
Packet body/payload.
Definition Packet.hpp:474
Header header
Packet header.
Definition Packet.hpp:473
static T from_network(T value)
Converts a primitive type (integer, float) from Big-Endian (network) to machine endianness.
Definition Packet.hpp:532
asio::ip::udp::socket & _serverUdpSocket
Reference to the server's UDP socket.
Definition Session.hpp:108
asio::ip::tcp::endpoint getTcpEndpoint() const
Set the TCP endpoint for the session.
Definition Session.cpp:73
void setUdpEndpoint(const asio::ip::udp::endpoint &endpoint)
Set the UDP endpoint for the session.
Definition Session.cpp:77
uint32_t getId() const
Get the unique identifier for the session.
Definition Session.cpp:69
bool _stopped
Flag indicating if the session is stopped.
Definition Session.hpp:105
std::mutex _writeMutex
Mutex for synchronizing write operations.
Definition Session.hpp:114
Session(uint32_t id, asio::ip::tcp::socket socket, asio::ip::udp::socket &serverUdpSocket, IEventPublisher &publisher)
Constructor for Session.
Definition Session.cpp:17
asio::steady_timer _timer
Timer for managing write operations.
Definition Session.hpp:115
bool _hasUdp
Flag indicating if UDP endpoint is set.
Definition Session.hpp:112
asio::ip::tcp::socket _socket
TCP socket associated with the session.
Definition Session.hpp:107
void setId(uint32_t id)
Set the unique identifier for the session.
Definition Session.cpp:65
void send(const Packet &packet, NetworkMode mode)
Send a packet to the client.
Definition Session.cpp:51
void stop(void)
Stop the session's operations.
Definition Session.cpp:43
asio::awaitable< void > writer(void)
Asynchronous writer coroutine for the session.
Definition Session.cpp:116
std::deque< Packet > _writeQueue
Queue of packets to be written to the TCP socket.
Definition Session.hpp:116
uint32_t _id
Unique identifier for the session.
Definition Session.hpp:104
~Session()
Destructor for Session.
Definition Session.cpp:29
IEventPublisher & _publisher
Reference to the event publisher for network events.
Definition Session.hpp:109
asio::ip::udp::endpoint _udpEndpoint
UDP endpoint associated with the session.
Definition Session.hpp:111
void start(void)
Start the session's read and write operations.
Definition Session.cpp:33
asio::awaitable< void > reader(void)
Asynchronous reader coroutine for the session.
Definition Session.cpp:86
File : IEventPublisher.hpp License: MIT Author : Elias Josué HAJJAR LLAUQUEN elias-josue....
constexpr uint16_t MAGIC_NUMBER
Magic number for packet validation.
Definition Packet.hpp:52
@ Disconnect
Disconnect notification.
NetworkMode
Enum representing network transmission modes.
Definition INetwork.hpp:25
STL namespace.
Packet header with sequencing and acknowledgment support.
Definition Packet.hpp:130
uint16_t ackId
Last acknowledged packet.
Definition Packet.hpp:134
uint16_t magic
Magic number for validation.
Definition Packet.hpp:131
uint16_t sequenceId
Packet sequence number.
Definition Packet.hpp:132
uint32_t sessionId
Session identifier.
Definition Packet.hpp:137
uint32_t bodySize
Size of the packet body.
Definition Packet.hpp:133