Boost Asio Peek and Completion Condition

2019-08-24 10:36发布

问题:

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:

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().