Reputation: 96547
Is it possible to use Boost's asio to do non-blocking IO without using async callbacks? I.e. equivalent to the O_NONBLOCK
socket option.
I basically want this function:
template<typename SyncWriteStream,
typename ConstBufferSequence>
std::size_t write_nonblock(
SyncWriteStream & s,
const ConstBufferSequence & buffers);
This function will write as many bytes as it can and return immediately. It may write 0 bytes.
Is it possible?
Upvotes: 1
Views: 4203
Reputation: 59
The way with s.non_blocking(true)
would not work.
If you check send
implementation, it uses socket_ops::sync_send
, which does poll_write
if send failed.
So it is still blocking on top level.
Upvotes: -1
Reputation: 157314
Yes, using the non_blocking()
method to put the socket into Asio non-blocking mode:
template<typename SyncWriteStream,
typename ConstBufferSequence>
std::size_t write_nonblock(
SyncWriteStream & s,
const ConstBufferSequence & buffers)
{
s.non_blocking(true);
boost::system::error_code ec;
auto bytes = s.send(buffers, 0, ec);
if (bytes == 0 && !(ec == boost::asio::error::would_block))
throw boost::system::system_error(ec, "write_nonblock send");
return bytes;
}
Upvotes: 3