srs-control 0.2.2
Loading...
Searching...
No Matches
SpecialSocketBase.cpp
Go to the documentation of this file.
4#include "srs/utils/UDPFormatters.hpp" // IWYU pragma: keep
5#include <asio/as_tuple.hpp>
6#include <asio/awaitable.hpp>
7#include <asio/ip/basic_endpoint.hpp>
8#include <asio/use_awaitable.hpp>
9#include <chrono>
10#include <future>
11#include <memory>
12#include <optional>
13#include <spdlog/spdlog.h>
14#include <system_error>
15
16namespace srs::connection
17{
18 SpecialSocket::SpecialSocket(int port_number, io_context_type& io_context)
19 : port_number_{ port_number }
20 , cancel_timer_{ io_context }
21 {
22 socket_ = std::make_unique<udp::socket>(io_context);
23 socket_->open(udp::v4());
24 cancel_timer_.expires_at(std::chrono::system_clock::time_point::max());
25 }
26
27 auto SpecialSocket::cancel_coroutine() -> asio::awaitable<void>
28 {
29 // NOLINTBEGIN (clang-analyzer-core.NullDereference)
30 [[maybe_unused]] auto err_code = co_await cancel_timer_.async_wait(asio::as_tuple(asio::use_awaitable));
31 // NOLINTEND (clang-analyzer-core.NullDereference)
32 spdlog::trace("Coroutine for the socket with local endpoint {} is cancelled.", socket_->local_endpoint());
33 }
34
35 auto SpecialSocket::bind_socket() -> std::error_code
36 {
37 auto local_endpoint = udp::endpoint{ udp::v4(), static_cast<asio::ip::port_type>(port_number_) };
38 spdlog::trace("Binding a socket to the local endpoint {}.", local_endpoint);
39 auto ec = std::error_code{};
40 socket_->bind(local_endpoint, ec);
41 return ec;
42 }
43
44 auto SpecialSocket::close_socket() -> std::error_code
45 {
46 auto err = std::error_code{};
47 socket_->close(err);
48 return err;
49 }
50
51 auto SpecialSocket::wait_for_listen_finish(std::chrono::seconds time) -> std::optional<std::future_status>
52 {
53 if (not listen_future_.valid())
54 {
55 return {};
56 }
57 return listen_future_.wait_for(time);
58 }
59} // namespace srs::connection
asio::system_timer cancel_timer_
Used for cancel the unfinished coroutine.
auto cancel_coroutine() -> asio::awaitable< void >
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
auto bind_socket() -> std::error_code
std::unique_ptr< udp::socket > socket_
SpecialSocket(int port_number, io_context_type &io_context)
Projected constructor, which can only be called from the derived classes.
std::shared_future< std::variant< std::monostate, std::monostate > > listen_future_
asio::thread_pool io_context_type