Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to asynchronously read to std::string using Boost::asio?
    primarykey
    data
    text
    <p>I'm learning Boost::asio and all that async stuff. How can I asynchronously read to variable <code>user_</code> of type std::string? <code>Boost::asio::buffer(user_)</code> works only with <code>async_write()</code>, but not with <code>async_read()</code>. It works with vector, so what is the reason for it not to work with string? Is there another way to do that besides declaring <code>char user_[max_len]</code> and using <code>Boost::asio::buffer(user_, max_len)</code>?</p> <p>Also, what's the point of inheriting from <code>boost::enable_shared_from_this&lt;Connection&gt;</code> and using <code>shared_from_this()</code> instead of <code>this</code> in <code>async_read()</code> and <code>async_write()</code>? I've seen that a lot in the examples.</p> <p>Here is a part of my code:</p> <pre><code>class Connection { public: Connection(tcp::acceptor &amp;acceptor) : acceptor_(acceptor), socket_(acceptor.get_io_service(), tcp::v4()) { } void start() { acceptor_.get_io_service().post( boost::bind(&amp;Connection::start_accept, this)); } private: void start_accept() { acceptor_.async_accept(socket_, boost::bind(&amp;Connection::handle_accept, this, placeholders::error)); } void handle_accept(const boost::system::error_code&amp; err) { if (err) { disconnect(); } else { async_read(socket_, boost::asio::buffer(user_), boost::bind(&amp;Connection::handle_user_read, this, placeholders::error, placeholders::bytes_transferred)); } } void handle_user_read(const boost::system::error_code&amp; err, std::size_t bytes_transferred) { if (err) { disconnect(); } else { ... } } ... void disconnect() { socket_.shutdown(tcp::socket::shutdown_both); socket_.close(); socket_.open(tcp::v4()); start_accept(); } tcp::acceptor &amp;acceptor_; tcp::socket socket_; std::string user_; std::string pass_; ... }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload