Kylin/AsioZeroMQ/SocketService.h
2023-07-21 14:07:27 +08:00

64 lines
2.1 KiB
C++

#ifndef SOCKETSERVICE_H
#define SOCKETSERVICE_H
#include "Options.h"
#include <boost/asio/execution_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <mutex>
namespace ZeroMQ {
#if !defined BOOST_ASIO_WINDOWS
struct StreamDescriptorClose {
void operator()(boost::asio::posix::stream_descriptor *descriptor) {
descriptor->release();
delete descriptor;
}
};
using StreamDescriptor = std::unique_ptr<boost::asio::posix::stream_descriptor, StreamDescriptorClose>;
using StreamType = boost::asio::posix::stream_descriptor;
using NativeHandleType = boost::asio::posix::stream_descriptor::native_handle_type;
#else
using StreamDescriptor = std::unique_ptr<boost::asio::ip::tcp::socket>;
using StreamType = boost::asio::ip::tcp::socket;
using NativeHandleType = boost::asio::ip::tcp::socket::native_handle_type;
#endif
class SocketService : public boost::asio::io_context::service {
public:
inline static boost::asio::execution_context::id id;
SocketService(boost::asio::io_context &context);
~SocketService();
class Implementation {
public:
Implementation(void *context, SocketType type, boost::asio::io_context &ioContext);
~Implementation();
void *socket;
StreamDescriptor descriptor;
std::mutex mutex;
};
using ImplementationType = std::shared_ptr<Implementation>;
void construct(ImplementationType &impl, SocketType type);
void destroy(ImplementationType &impl);
void connect(ImplementationType &impl, std::string_view endpoint, boost::system::error_code &error);
void setOption(ImplementationType &impl, int option, const void *optval, size_t optvallen,
boost::system::error_code &error);
void option(const ImplementationType &impl, int option, void *optval, size_t *optvallen,
boost::system::error_code &error);
/// Destroy all user-defined handler objects owned by the service.
void shutdown() {}
private:
void *m_context;
};
} // namespace ZeroMQ
#endif // SOCKETSERVICE_H