26 UDP::UDP(asio::io_context &io_context,
const std::string &ip,
int port,
bool is_sender)
27 : _socket(io_context), _is_sender(is_sender)
30 _socket.open(asio::ip::udp::v4());
32 asio::ip::udp::endpoint endpoint(asio::ip::address::from_string(ip), port);
33 _socket.open(endpoint.protocol());
34 _socket.bind(endpoint);
36 _socket.non_blocking(
true);
54 void UDP::sendTo(
const std::string &message,
const std::string &address,
int port)
56 asio::ip::udp::endpoint endpoint(asio::ip::address::from_string(address), port);
57 _socket.send_to(asio::buffer(message), endpoint);
68 void UDP::sendRaw(
const char *data, std::size_t size,
const std::string &address,
int port)
70 asio::ip::udp::endpoint endpoint(asio::ip::address::from_string(address), port);
71 _socket.send_to(asio::buffer(data, size), endpoint);
84 asio::ip::udp::endpoint sender_endpoint;
87 size_t len = _socket.receive_from(asio::buffer(buffer), sender_endpoint, 0, ec);
89 if (ec == asio::error::would_block) {
96 throw std::runtime_error(
"Receive failed: " + ec.message());
99 address = sender_endpoint.address().to_string();
100 port = sender_endpoint.port();
102 std::string received_data(buffer, len);
103 _received_packets.push(received_data);
104 return received_data;
114 return _socket.is_open();
124 if (_received_packets.empty()) {
127 std::string packet = _received_packets.front();
128 _received_packets.pop();
#define PRETTY_WARNING
Warning log with details and colour.
This file contains the definition of the UDP class for handling UDP network communication.
std::string fetchPacket()
Fetch a packet from the received packets queue.
void sendRaw(const char *data, std::size_t size, const std::string &address, int port)
Send raw data to a specified address and port.
UDP(asio::io_context &io_context, const std::string &ip, int port, bool is_sender)
Construct a new UDP object.
~UDP()
Destroy the UDP object.
void sendTo(const std::string &message, const std::string &address, int port)
Send a message to a specified address and port.
bool isConnectionAlive()
Check if the connection is alive.
std::string receiveFrom(std::string &address, int &port)
Receive a message from a specified address and port.