简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM