54 using OnReceive = std::function<PacketList(PacketList&& packets)>;
57 virtual int sendTo(
const SockAddr& dest,
const uint8_t* data,
size_t size,
bool replied) = 0;
59 inline void setOnReceive(OnReceive&& cb)
61 std::lock_guard<std::mutex> lk(lock);
62 rx_callback = std::move(cb);
65 virtual bool hasIPv4()
const = 0;
66 virtual bool hasIPv6()
const = 0;
68 SockAddr getBound(sa_family_t family = AF_UNSPEC)
const
70 std::lock_guard<std::mutex> lk(lock);
71 return getBoundRef(family);
73 in_port_t getPort(sa_family_t family = AF_UNSPEC)
const
75 std::lock_guard<std::mutex> lk(lock);
76 return getBoundRef(family).getPort();
79 virtual const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC)
const = 0;
82 virtual std::vector<SockAddr>
resolve(
const std::string& host,
const std::string& service = {})
84 return SockAddr::resolve(host, service);
87 virtual void stop() = 0;
90 PacketList getNewPacket()
93 if (toRecycle_.empty()) {
96 auto begIt = toRecycle_.begin();
97 auto begItNext = std::next(begIt);
98 pkts.splice(pkts.end(), toRecycle_, begIt, begItNext);
103 inline void onReceived(PacketList&& packets)
105 std::lock_guard<std::mutex> lk(lock);
107 auto r = rx_callback(std::move(packets));
108 if (not r.empty() and toRecycle_.size() < RX_QUEUE_MAX_SIZE)
109 toRecycle_.splice(toRecycle_.end(), std::move(r));
114 mutable std::mutex lock;
117 OnReceive rx_callback;
118 PacketList toRecycle_;
124 UdpSocket(in_port_t port,
const std::shared_ptr<Logger>& l = {});
125 UdpSocket(
const SockAddr& bind4,
const SockAddr& bind6,
const std::shared_ptr<Logger>& l = {});
128 int sendTo(
const SockAddr& dest,
const uint8_t* data,
size_t size,
bool replied)
override;
130 const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC)
const override
132 return (family == AF_INET6) ? bound6 : bound4;
135 bool hasIPv4()
const override
137 std::lock_guard<std::mutex> lk(lock);
140 bool hasIPv6()
const override
142 std::lock_guard<std::mutex> lk(lock);
146 void stop()
override;
149 std::shared_ptr<Logger> logger;
154 std::thread rcv_thread {};
155 std::atomic_bool running {
false};