Код: Выделить всё
#pragma once
#include
#include
#include
#include
#include
class SocketWrapper
{
private:
using SslStream = boost::asio::ssl::stream;
public:
// A universal version of asyncRead that supports the both callbacks and coroutines.
// It is not a coroutine itself, because it does not use co_return or co_await.
template
boost::asio::experimental::promise
asyncRead(uint8_t (&data)[read_length])
{
auto buf = boost::asio::buffer(data, read_length);
return isSSL() ? stream().async_read_some(buf, boost::asio::experimental::use_promise)
: underlyingSocket().async_read_some(buf, boost::asio::experimental::use_promise);
}
// A version of asyncRead accepting a callback.
template
requires std::invocable
void asyncRead(uint8_t (&data)[read_length], Func&& func)
{
auto promise = asyncRead(data);
promise(std::forward(func));
}
private:
bool isSSL() const;
const boost::asio::ip::tcp::socket& underlyingSocket() const;
boost::asio::ip::tcp::socket& underlyingSocket();
const SslStream& stream() const;
SslStream& stream();
};
void handleRead(
const boost::system::error_code& error,
const std::size_t bytesTransferred);
void someRead()
{
static SocketWrapper wrapper;
uint8_t data[1024];
wrapper.asyncRead(
data,
boost::bind(
&handleRead,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
Второй предназначен для использования с обратными вызовами, но я не уверен, что написал его правильно, поскольку в моем проекте обратный вызов вызывается с ошибкой. Действительно ли экспериментальный::promise::operator() принимает обратный вызов или что-то еще? см. его документацию.
Подробнее здесь: https://stackoverflow.com/questions/797 ... talpromise
Мобильная версия