cancel operation

This commit is contained in:
Антон 2024-04-05 23:11:42 +03:00
parent cf37d36353
commit b96e9e885f
2 changed files with 81 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,76 @@
#include <boost/predef.h>
#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 <boost/asio.hpp>
#include <iostream>
#include <string>
#include <thread>
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<net::ip::tcp::socket>(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)
{
}
}