3#include <ossia/network/sockets/configuration.hpp>
5#include <boost/asio/io_context.hpp>
6#include <boost/asio/ip/udp.hpp>
7#include <boost/asio/local/datagram_protocol.hpp>
8#include <boost/asio/placeholders.hpp>
9#include <boost/asio/strand.hpp>
10#include <boost/asio/write.hpp>
12#include <nano_signal_slot.hpp>
17class udp_receive_socket
19 using proto = boost::asio::ip::udp;
22 udp_receive_socket(boost::asio::io_context& ctx)
24 , m_socket{boost::asio::make_strand(ctx)}
28 udp_receive_socket(
const inbound_socket_configuration& conf, boost::asio::io_context& ctx)
30 , m_endpoint{boost::asio::ip::make_address(conf.bind), conf.port}
31 , m_socket{boost::asio::make_strand(ctx)}
35 ~udp_receive_socket() =
default;
37 void assign(
int sock) { m_socket.assign(boost::asio::ip::udp::v4(), sock); }
40 m_socket.open(boost::asio::ip::udp::v4());
41 m_socket.bind(m_endpoint);
46 if(m_socket.is_open())
48 boost::asio::post(m_context, [
this] {
58 m_socket.async_receive_from(
59 boost::asio::mutable_buffer(&m_data[0], std::size(m_data)), m_endpoint,
60 [
this, f](
auto ec, std::size_t sz) {
61 if(ec == boost::asio::error::operation_aborted)
70 catch(
const std::exception& e)
76 ossia::logger().error(
"[udp_socket::receive]: unknown error");
84 Nano::Signal<void()> on_close;
86 boost::asio::io_context& m_context;
87 proto::endpoint m_endpoint;
88 proto::socket m_socket;
89 alignas(16)
char m_data[65535];
94 using proto = boost::asio::ip::udp;
97 udp_send_socket(
const outbound_socket_configuration& conf, boost::asio::io_context& ctx)
99 , m_endpoint{boost::asio::ip::make_address(conf.host), conf.port}
100 , m_socket{boost::asio::make_strand(ctx)}
101 , m_broadcast{conf.broadcast}
106 const boost::asio::ip::address& host,
const uint16_t port,
107 boost::asio::io_context& ctx)
109 , m_endpoint{host, port}
110 , m_socket{boost::asio::make_strand(ctx)}
116 m_socket.open(boost::asio::ip::udp::v4());
118 m_socket.set_option(boost::asio::ip::udp::socket::reuse_address(
true));
121 m_socket.set_option(boost::asio::socket_base::broadcast(
true));
126 if(m_socket.is_open())
128 boost::asio::post(m_context, [
this] {
135 void write(
const proto::endpoint& ep,
const char* data, std::size_t sz)
137 boost::system::error_code ec;
138 m_socket.send_to(boost::asio::const_buffer(data, sz), ep, 0, ec);
141 void write(
const char* data, std::size_t sz) { write(m_endpoint, data, sz); }
143 Nano::Signal<void()> on_close;
145 boost::asio::io_context& m_context;
146 proto::endpoint m_endpoint;
147 proto::socket m_socket;
spdlog::logger & logger() noexcept
Where the errors will be logged. Default is stderr.
Definition context.cpp:118