0
votes

I am using Boost Asio to set up a socket connection. I would like to peek at the data in the buffer without consuming it, and I would like to use a completion condition to ensure that I could stop the blocking call if necessary.

I can get the peek functionality from basic_stream_socket::receive:

template<
    typename MutableBufferSequence>
std::size_t receive(
    const MutableBufferSequence & buffers,
    socket_base::message_flags flags,
    boost::system::error_code & ec);

One of the possible message_flags is basic_stream_socket::message_peek. However, this call blocks until at least one byte is read or an error occurs. I can get the completion condition functionality from read:

template<
    typename SyncReadStream,
    typename MutableBufferSequence,
    typename CompletionCondition>
std::size_t read(
    SyncReadStream & s,
    const MutableBufferSequence & buffers,
    CompletionCondition completion_condition,
    boost::system::error_code & ec);

I can provide a completion_condition method which checks if the call should be aborted before continuing.

My question is this: Is there a way to get a message_flags parameter and a completion_condition parameter in the same method call?

1
why not use async operations, then you don't need to worry - no calls will be blocking, and you'll be notified when there is data. - Nim
I would still have the problem of not being able to stop the pending operation if needed. I could do an async operation if it had both the ability to peek and to provide a completion condition, but if I used an async method (like async_receive) I'm not sure how to cancel the operation if necessary. - Brian
For a given socket, you can cancel outstanding asynchronous operations. - Nim

1 Answers

1
votes

I would like to peek at the data in the buffer without consuming it, and I would like to use a completion condition to ensure that I could stop the blocking call if necessary.

Don't do this. Use asynchronous methods such as async_read() and async_write(). To stop outstanding asynchronous operations, use cancel().