Alon
Alon

Reputation: 1804

boost asio cancelling read without cancelling write

I have a socket that both waits for data and tries to send some as well(async_read / async_write), at some point I'd like to cancel the read only, possibly re-initializing it at a later stage.

Is it possible?

Upvotes: 2

Views: 950

Answers (2)

ComicSansMS
ComicSansMS

Reputation: 54589

Aborting a specific asynchronous operation in asio is unfortunately rather difficult. Usually, reliably aborting pending asynchronous operations is only possible by closing the socket completely.

In practice, this is less of a limitation than one might think: If you allow asynchronous operations to be canceled at any point it becomes very hard to reason about the state of the connection. In your example, even if you cancel the undesired read, the data it was supposed to retrieve still has to be removed from the socket, so that a subsequent read can start with a clean state. This is very difficult to ensure at this level of control.

Instead, consider having the async read operation finish and use the program logic to determine what to do with the read data: If the operation is marked as canceled, you might simply want to discard the data.

Upvotes: 2

Evgeny Lazin
Evgeny Lazin

Reputation: 9413

Maybe you need to shutdown your socket?

socket.shutdown(boost::asio::ip::tcp::socket::shutdown_receive);

after call to shutdown your socket will be unable to receive new data.

Upvotes: 1

Related Questions