67 using OnReceive = std::function<PacketList(PacketList&& packets)>;
70 virtual int sendTo(
const SockAddr& dest,
const uint8_t* data,
size_t size,
bool replied) = 0;
72 inline void setOnReceive(OnReceive&& cb) {
73 std::lock_guard<std::mutex> lk(lock);
74 rx_callback = std::move(cb);
77 virtual bool hasIPv4()
const = 0;
78 virtual bool hasIPv6()
const = 0;
80 SockAddr getBound(sa_family_t family = AF_UNSPEC)
const {
81 std::lock_guard<std::mutex> lk(lock);
82 return getBoundRef(family);
84 in_port_t getPort(sa_family_t family = AF_UNSPEC)
const {
85 std::lock_guard<std::mutex> lk(lock);
86 return getBoundRef(family).getPort();
89 virtual const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC)
const = 0;
92 virtual std::vector<SockAddr>
resolve(
const std::string& host,
const std::string& service = {}) {
93 return SockAddr::resolve(host, service);
96 virtual void stop() = 0;
99 PacketList getNewPacket() {
101 if (toRecycle_.empty()) {
104 auto begIt = toRecycle_.begin();
105 auto begItNext = std::next(begIt);
106 pkts.splice(pkts.end(), toRecycle_, begIt, begItNext);
111 inline void onReceived(PacketList&& packets) {
112 std::lock_guard<std::mutex> lk(lock);
114 auto r = rx_callback(std::move(packets));
115 if (not r.empty() and toRecycle_.size() < RX_QUEUE_MAX_SIZE)
116 toRecycle_.splice(toRecycle_.end(), std::move(r));
120 mutable std::mutex lock;
122 OnReceive rx_callback;
123 PacketList toRecycle_;
128 UdpSocket(in_port_t port,
const std::shared_ptr<Logger>& l = {});
129 UdpSocket(
const SockAddr& bind4,
const SockAddr& bind6,
const std::shared_ptr<Logger>& l = {});
132 int sendTo(
const SockAddr& dest,
const uint8_t* data,
size_t size,
bool replied)
override;
134 const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC)
const override {
135 return (family == AF_INET6) ? bound6 : bound4;
138 bool hasIPv4()
const override {
139 std::lock_guard<std::mutex> lk(lock);
142 bool hasIPv6()
const override {
143 std::lock_guard<std::mutex> lk(lock);
147 void stop()
override;
149 std::shared_ptr<Logger> logger;
154 std::thread rcv_thread {};
155 std::atomic_bool running {
false};