7#include <asio/as_tuple.hpp>
8#include <asio/awaitable.hpp>
9#include <asio/buffer.hpp>
10#include <asio/experimental/awaitable_operators.hpp>
11#include <asio/system_timer.hpp>
12#include <asio/this_coro.hpp>
13#include <asio/use_awaitable.hpp>
14#include <asio/use_future.hpp>
20#include <fmt/ranges.h>
24#include <spdlog/spdlog.h>
25#include <system_error>
39 template <
typename SocketType>
41 requires(SocketType socket, std::shared_ptr<typename SocketType::ConnectionType>
connection) {
42 requires std::derived_from<SocketType, SpecialSocket>;
43 requires not std::is_same_v<SocketType, SpecialSocket>;
45 asio::mutable_buffer{ socket.get_response_msg_buffer() };
49 { socket.response_handler(
UDPEndpoint{}, std::size_t{}) } -> std::same_as<void>;
50 { socket.is_finished() } -> std::same_as<bool>;
51 { socket.print_error() } -> std::same_as<void>;
52 { socket.register_send_action_imp(asio::awaitable<void>{},
connection) } -> std::same_as<void>;
58 class SpecialSocket :
public std::enable_shared_from_this<SpecialSocket>
63 -> std::expected<std::shared_ptr<SocketType>, std::error_code>;
76 asio::awaitable<void> action,
77 const std::shared_ptr<
typename std::remove_cvref_t<
decltype(self)>::ConnectionType>&
connection);
97 std::chrono::seconds waiting_time = std::chrono::seconds(2)) -> std::future<void>;
174 [[maybe_unused]] std::chrono::steady_clock
clock_;
175 std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds>
time_point_;
185 template <SpecialSocketDerived SocketType>
191 -> std::expected<std::shared_ptr<SocketType>, std::error_code>
194 std::shared_ptr<SocketType>(
new SocketType{ port_number, io_context, std::forward<Args>(args)... });
195 auto error_code = socket->bind_socket();
198 spdlog::critical(
"Local socket failed to bind to the port {} due to the error: {}",
200 error_code.message());
201 return std::unexpected{ error_code };
203 socket->listen(io_context);
207 template <SpecialSocketDerived SocketType>
210 const auto port_str = fmt::format(
"{}", socket->get_port());
212 auto remote_endpoint = udp::endpoint{};
213 spdlog::debug(
"Local socket with endpoint {} starts to listen ...", socket->get_socket().local_endpoint());
216 const auto [err_code, receive_size] =
co_await socket->get_socket().async_receive_from(
217 asio::mutable_buffer{ socket->get_response_msg_buffer() },
219 asio::as_tuple(asio::use_awaitable));
221 socket->time_point_ = socket->clock_.now();
225 socket->response_handler(remote_endpoint, receive_size);
232 ++socket->n_records_;
233 socket->n_bytes += receive_size;
234 socket->total_time_ns_ +=
static_cast<uint64_t
>((socket->clock_.now() - socket->time_point_).count());
237 socket->before_socket_close();
238 if (
auto err = socket->close_socket(); err)
240 spdlog::error(
"Error occurred when closing the socket with local endpoint {}: {}",
241 socket->get_socket().local_endpoint(),
245 spdlog::trace(
"Coroutine for the local socket with port {} has existed.", socket->get_port());
251 asio::awaitable<void> action,
252 const std::shared_ptr<
typename std::remove_cvref_t<
decltype(self)>::ConnectionType>&
connection)
254 spdlog::trace(
"Registering send action from connection {} with remote endpoint {}.",
257 self.register_send_action_imp(std::move(action),
connection);
258 spdlog::trace(
"Send action to the remote endpoint {} has been registered.",
265 using asio::experimental::awaitable_operators::operator||;
266 self.listen_future_ =
267 asio::co_spawn(io_context,
275 std::chrono::seconds waiting_time) -> std::future<void>
277 auto waiting_action = [](
auto socket, std::chrono::seconds waiting_time) -> asio::awaitable<void>
279 auto is_finished =
false;
280 spdlog::trace(
"Waiting local socket with port {} to finish listening ...", socket->get_port());
281 auto timer = asio::system_timer{
co_await asio::this_coro::executor };
282 if (socket->is_finished())
284 spdlog::trace(
"Local socket with port {} finished listening and is cancelled immediately.",
286 timer.expires_after(std::chrono::seconds(0));
291 timer.expires_after(waiting_time);
293 [[maybe_unused]]
auto err_code =
co_await timer.async_wait(asio::as_tuple(asio::use_awaitable));
294 socket->cancel_timer_.cancel();
295 if (not is_finished and not socket->is_finished())
297 socket->print_error();
300 return asio::co_spawn(
Base socket class for sending and listening messages.
auto cancel_listen_after(this auto &&self, io_context_type &io_context, std::chrono::seconds waiting_time=std::chrono::seconds(2)) -> std::future< void >
Cancelling the listening action after a certain time.
asio::system_timer cancel_timer_
Used for cancel the unfinished coroutine.
auto cancel_coroutine() -> asio::awaitable< void >
auto get_cancel_timer() -> auto &
auto get_total_time_ns() const -> std::uint64_t
Getter for the total listening time in nano seconds.
auto get_n_records() const -> std::size_t
Getter for the number of frames read.
static auto create(int port_number, io_context_type &io_context, Args &&... args) -> std::expected< std::shared_ptr< SocketType >, std::error_code >
std::chrono::steady_clock clock_
auto wait_for_listen_finish(std::chrono::seconds time) -> std::optional< std::future_status >
Blocking the current thread by waiting the listen action to finish until a certain time duration.
auto close_socket() -> std::error_code
std::chrono::time_point< std::chrono::steady_clock, std::chrono::nanoseconds > time_point_
auto bind_socket() -> std::error_code
std::unique_ptr< udp::socket > socket_
void set_report(AppReport *report)
auto get_future() -> auto &
Getter for the status of the listen action.
void listen(this auto &self, io_context_type &io_context)
Listen to any UDP data.
static auto async_listen_all_connections(std::shared_ptr< SocketType > socket) -> asio::awaitable< void >
auto get_n_bytes() const -> std::size_t
Getter for the number of bytes read.
auto get_report() -> auto *
SpecialSocket(int port_number, io_context_type &io_context)
Projected constructor, which can only be called from the derived classes.
auto get_port() const -> int
Getter for the port number.
void register_send_action(this auto &&self, asio::awaitable< void > action, const std::shared_ptr< typename std::remove_cvref_t< decltype(self)>::ConnectionType > &connection)
Registering the send action.
std::uint64_t total_time_ns_
std::shared_future< std::variant< std::monostate, std::monostate > > listen_future_
void before_socket_close()
auto get_socket() const -> udp::socket &
Getter for the asio udp socket object.
constexpr auto get_shared_from_this(auto &&obj)
asio::ip::basic_endpoint< asio::ip::udp > UDPEndpoint
asio::thread_pool io_context_type