122 lines
3.0 KiB
C++
122 lines
3.0 KiB
C++
#pragma once
|
|
|
|
/*
|
|
|
|
ABSTRACT DEVICE COMPONENTS LIBRARY
|
|
|
|
ASIO-library implementation of network server session
|
|
|
|
*/
|
|
|
|
#ifdef USE_ASIO_LIBRARY
|
|
|
|
#include "adc_netservice_asio.h"
|
|
|
|
// #ifdef USE_SPDLOG_LIBRARY
|
|
// #include "adc_netserver_spdlog.h"
|
|
// #endif // USE_SPDLOG_LIBRARY
|
|
|
|
|
|
namespace adc::impl
|
|
{
|
|
|
|
template <traits::adc_netservice_asio_c NetServiceT, typename ContextT = std::nullptr_t>
|
|
class AdcNetServerSessionASIO : std::enable_shared_from_this<AdcNetServerSessionASIO<NetServiceT, ContextT>>
|
|
{
|
|
public:
|
|
typedef std::string_view session_ident_t;
|
|
|
|
typedef NetServiceT netservice_t;
|
|
|
|
typedef ContextT context_t;
|
|
|
|
typedef std::chrono::duration<double, std::milli> timeout_t;
|
|
|
|
static constexpr timeout_t defaultSendTimeout = std::chrono::milliseconds(5000); // 5 seconds
|
|
static constexpr timeout_t defaultRecvTimeout =
|
|
std::chrono::hours(12); // actualy, it is a time to wait something from client
|
|
|
|
template <traits::adc_input_char_range R>
|
|
AdcNetServerSessionASIO(std::shared_ptr<netservice_t>& net_service,
|
|
const R& sess_ident,
|
|
ContextT&& context = nullptr)
|
|
: _socket(net_service.get_executor()),
|
|
// _socket(std::move(sock)),
|
|
_netService(_socket),
|
|
_sessionIdent(sess_ident.begin(), sess_ident.end()),
|
|
_context(context),
|
|
_sendTimeout(defaultSendTimeout),
|
|
_recvTimeout(defaultRecvTimeout)
|
|
{
|
|
// generic implementation
|
|
_stopFunc = [net_service = net_service]() { net_service->close(); };
|
|
|
|
_startFunc = [this]() { acceptMessage(); };
|
|
|
|
_acceptMessageFunc = [net_service = net_service, this]() {
|
|
net_service->asynReceive<NetMessageT>(
|
|
_recvTimeout, [self = this->shared_from_this(), this](std::error_code ec, const auto& mess) {
|
|
if (ec) {
|
|
stop();
|
|
} else {
|
|
acceptMessage();
|
|
}
|
|
});
|
|
};
|
|
}
|
|
|
|
|
|
virtual ~AdcNetServerSessionASIO()
|
|
{
|
|
stop();
|
|
}
|
|
|
|
template <traits::adc_time_duration_c TimeoutT>
|
|
AdcNetServerSessionASIO& setDefaultTimeouts(const TimeoutT& send_timeout = defaultSendTimeout,
|
|
const TimeoutT& recv_timeout = defaultRecvTimeout)
|
|
{
|
|
_sendTimeout = send_timeout;
|
|
_recvTimeout = recv_timeout;
|
|
|
|
return *this;
|
|
}
|
|
|
|
session_ident_t sessionIdent() const
|
|
{
|
|
return {_sessionIdent.begin(), _sessionIdent.end()};
|
|
}
|
|
|
|
|
|
virtual void start()
|
|
{
|
|
_startFunc();
|
|
}
|
|
|
|
|
|
virtual void stop()
|
|
{
|
|
_stopFunc();
|
|
}
|
|
|
|
protected:
|
|
netservice_t::socket_t _socket;
|
|
netservice_t _netService;
|
|
|
|
std::string _sessionIdent;
|
|
ContextT _context;
|
|
|
|
timeout_t _sendTimeout, _recvTimeout;
|
|
|
|
std::function<void()> _startFunc, _stopFunc, _acceptMessageFunc;
|
|
|
|
virtual void acceptMessage()
|
|
{
|
|
_acceptMessageFunc();
|
|
}
|
|
};
|
|
|
|
} // namespace adc::impl
|
|
|
|
|
|
#endif // USE_ASIO_LIBRARY
|