boost_asio/boost_boilerplate/src/chapter02_io/cancel_async_operations.cpp

77 lines
1.7 KiB
C++

#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)
{
cout << "Error!" << err.what() << endl;
}
}