I have a program (client + server) that works without problems with this entry:
boost::asio::write(this->socket_, boost::asio::buffer(message.substr(count,length_to_send)));
where socket_- boost::asio::ssl::stream<boost::asio::ip::tcp::socket>, and message- std::string.
I would like to do it better and not block, so I created a function that could replace this, it was called the following:
write_async_sync(socket_,message.substr(count,length_to_send));
The purpose of this function:
- To make the call asynchronous internally
- To keep the interface intact
The function I implemented just uses perspective / future to simulate the synchronization behavior, which I will change later (after its operation) to cancel:
std::size_t
SSLClient::write_async_sync(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& socket,
const std::string& message_to_send)
{
boost::system::error_code write_error;
std::promise<std::size_t> write_promise;
auto write_future = write_promise.get_future();
boost::asio::async_write(socket,
boost::asio::buffer(message_to_send),
[this,&write_promise,&write_error,&message_to_send]
(const boost::system::error_code& error,
std::size_t size_written)
{
logger.write("HANDLING WRITING");
if(!error)
{
write_error = error;
write_promise.set_value(size_written);
}
else
{
write_promise.set_exception(std::make_exception_ptr(std::runtime_error(error.message())));
}
});
std::size_t size_written = write_future.get();
return size_written;
}
Problem: I cannot get asynchronous functions to work. Synchronization works fine, but asynchronously just freezes and never enters the lambda part (the letter never happens). What am I doing wrong?
: , poll_one() , , . run() io_service ( ):
io_service_work = std::make_shared<boost::asio::io_service::work>(io_service);
io_service_thread.reset(new std::thread([this](){io_service.run();}));
shared_ptr. ? poll_one()?