Kylin/Nng/SocketAisoWrapper.h
2024-10-29 13:51:37 +00:00

48 lines
1.5 KiB
C++

#ifndef __SOCKETAISOWRAPPER_H__
#define __SOCKETAISOWRAPPER_H__
#include "Socket.h"
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/post.hpp>
namespace Nng {
namespace Asio {
class Socket : public Nng::Socket {
public:
Socket(boost::asio::io_context &ioContex, Protocol protocol);
template <typename ReadHandler>
void asyncReceive(ReadHandler &&handler) {
void *data;
size_t size;
int status = nng_recv(m_socket, &data, &size, NNG_FLAG_NONBLOCK | NNG_FLAG_ALLOC);
if (status == 0) {
boost::asio::post(m_descriptor->get_executor(), [data, size, handler{std::move(handler)}]() {
boost::system::error_code error;
handler(error, Buffer(data, size));
});
} else {
m_descriptor->async_wait(boost::asio::posix::stream_descriptor::wait_read,
[this, handler{std::move(handler)}](const boost::system::error_code &waitError) {
if (waitError) {
return handler(waitError, {});
}
auto buffer = recv();
return handler(waitError, buffer);
});
}
}
private:
std::unique_ptr<boost::asio::posix::stream_descriptor> m_descriptor;
};
}; // namespace Asio
}; // namespace Nng
#endif // __SOCKETAISOWRAPPER_H__