diff --git a/boost_boilerplate/CMakeLists.txt b/boost_boilerplate/CMakeLists.txt index ca287b3..88d108c 100644 --- a/boost_boilerplate/CMakeLists.txt +++ b/boost_boilerplate/CMakeLists.txt @@ -93,3 +93,8 @@ add_executable(reading_tcp_async src/chapter02_io/reading_tcp_async.cpp src/sdk.h) target_link_libraries(reading_tcp_async PRIVATE Threads::Threads) + +add_executable(cancel_async_operations + src/chapter02_io/cancel_async_operations.cpp + src/sdk.h) +target_link_libraries(cancel_async_operations PRIVATE Threads::Threads) diff --git a/boost_boilerplate/src/chapter02_io/cancel_async_operations.cpp b/boost_boilerplate/src/chapter02_io/cancel_async_operations.cpp new file mode 100644 index 0000000..831237a --- /dev/null +++ b/boost_boilerplate/src/chapter02_io/cancel_async_operations.cpp @@ -0,0 +1,76 @@ +#include + +#ifdef BOOST_OS_WINDOWS +#define _WIN32_WINNT 0x0501 + +#if _WIN32_WINNT <= 0x0502 + +#define BOOST_ASIO_DISABLE_IOCF +#define BOOST_ASIO_ENABLE_CANCELIO +#endif +#endif + +#include +#include +#include +#include + +using namespace boost; +namespace net = boost::asio; +namespace sys = boost::system; +using namespace std; + +int main() +{ + string raw_ip_address = "127.0.0.1"; + const uint16_t port_num = 3333; + + try + { + net::ip::tcp::endpoint ep(net::ip::address::from_string(raw_ip_address), port_num); + net::io_context ios; + + auto sock = make_shared(ios, ep.protocol()); + + sock->async_connect(ep, [sock](const sys::error_code& ec) + { + if (ec) + { + if (ec == net::error::operation_aborted) + { + cout << "Operation cancelled"; + } + else + { + cout << "Error occured" + << "\nError code = " << ec.value() + << "\nMessage: " << ec.what(); + } + + return; + } + }); + + thread worker_thread([&ios]() + { + try + { + ios.run(); + } + catch (const sys::system_error& err) + { + cout << "Error occured" + << "\nError code = " << err.code() + << "\nMessage: " << err.what(); + } + }); + + this_thread::sleep_for(chrono::seconds(2)); + sock->cancel(); + worker_thread.join(); + } + catch (const sys::system_error& err) + { + + } +}