13 : socket_(std::move(socket))
19 std::function<
void(
const std::vector<uint8_t>&,
20 const asio::ip::udp::endpoint&)> callback) ->
void
22 std::lock_guard<std::mutex> lock(callback_mutex_);
23 receive_callback_ = std::move(callback);
27 std::function<
void(std::error_code)> callback) ->
void
29 std::lock_guard<std::mutex> lock(callback_mutex_);
30 error_callback_ = std::move(callback);
36 is_receiving_.store(
true);
43 is_receiving_.store(
false);
49 is_closed_.store(
true);
66 if (!is_receiving_.load())
71 auto self = shared_from_this();
72 socket_.async_receive_from(
73 asio::buffer(read_buffer_),
75 [
this, self](std::error_code ec, std::size_t length)
78 if (!is_receiving_.load())
86 if constexpr (std::is_invocable_v<
decltype(error_callback_),
89 std::lock_guard<std::mutex> lock(callback_mutex_);
101 if constexpr (std::is_invocable_v<
decltype(receive_callback_),
102 const std::vector<uint8_t>&,
103 const asio::ip::udp::endpoint&>)
105 std::vector<uint8_t> datagram(read_buffer_.begin(),
106 read_buffer_.begin() + length);
107 std::lock_guard<std::mutex> lock(callback_mutex_);
108 if (receive_callback_)
110 receive_callback_(datagram, sender_endpoint_);
116 if (is_receiving_.load())
124 std::vector<uint8_t>&& data,
125 const asio::ip::udp::endpoint& endpoint,
126 std::function<
void(std::error_code, std::size_t)> handler) ->
void
128 auto self = shared_from_this();
130 auto buffer = std::make_shared<std::vector<uint8_t>>(std::move(data));
131 socket_.async_send_to(
132 asio::buffer(*buffer),
134 [handler = std::move(handler), self, buffer](std::error_code ec,
135 std::size_t bytes_transferred)
137 if constexpr (std::is_invocable_v<
decltype(handler),
138 std::error_code, std::size_t>)
142 handler(ec, bytes_transferred);
auto do_receive() -> void
Internal function to handle the receive logic with async_receive_from().
auto async_send_to(std::vector< uint8_t > &&data, const asio::ip::udp::endpoint &endpoint, std::function< void(std::error_code, std::size_t)> handler) -> void
Initiates an asynchronous send of the given data to endpoint.
auto is_closed() const -> bool
Checks if the socket has been closed.
auto stop_receive() -> void
Stops the receive loop to prevent further async operations.
auto start_receive() -> void
Begins the continuous asynchronous receive loop.
udp_socket(asio::ip::udp::socket socket)
Constructs a udp_socket by taking ownership of a moved socket.
std::atomic< bool > is_closed_
auto set_receive_callback(std::function< void(const std::vector< uint8_t > &, const asio::ip::udp::endpoint &)> callback) -> void
Sets a callback to receive inbound datagrams.
auto close() -> void
Safely closes the socket and stops all async operations.
auto set_error_callback(std::function< void(std::error_code)> callback) -> void
Sets a callback to handle socket errors (e.g., receive/send failures).