Consider the following code:
void TCP::sendMessage(const std::string& msg) {
std::ostream os{&m_send_streambuf};
os << msg;
if (not m_pending_send) {
doSend();
}
}
void TCP::doSend() {
m_pending_send = true;
boost::asio::async_write( m_socket, m_send_streambuf
, [this](boost::system::error_code ec, std::size_t len)
{
if (ec) {
throw std::runtime_error(ec.message());
}
m_send_streambuf.consume(len);
if (m_send_streambuf.size() >= 1) {
// There's still some data to send
doSend();
}
else {
m_pending_send = false;
}
});
}
m_send_streambuf
is a boost::asio::streambuf
and m_pending_send
indicates wether an asynchronous write is pending.
I'm not sure if it's a good idea to use the streambuf
like this as a call to sendMessage
will modify the buffer, while an asynchronous write is possibly running.
So, is it safe to use the streambuf
like this? Or maybe I should use some kind of double buffering?