Asynchronous operations do not complete immediately. Your code looks like you expect them to.
Simplifying your code to:
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::udp;
int main() {
std::cout << std::boolalpha;
boost::asio::io_context io;
boost::asio::ip::udp::socket s {io, udp::v4()};
boost::asio::ip::udp::endpoint const ep {{}, 9999};
auto trace = [&s](char const* caption) { std::cout << caption << s.is_open() << std::endl; };
auto handler = [=](boost::system::error_code, size_t) { trace("handler: "); };
trace("main #1: ");
char buff[200] = {};
s.async_send_to(boost::asio::buffer(buff), ep, handler);
trace("main #2: ");
s.close();
s.async_send_to(boost::asio::buffer(buff), ep, handler);
trace("main #3: ");
s.close();
io.run();
}
It makes sense that the handler only run AFTER io.run()
; And obviously the socket is only "open" until it got first closed:
main #1: true
main #2: true
main #3: false
handler: false
handler: false
This is exactly expected. So, either you should handle errors:
Live On Coliru
auto trace = [&s](char const* caption) { std::cout << caption << (s.is_open()?"open":"closed") << std::endl; };
auto handler = [=](boost::system::error_code ec, size_t) {
trace(("handler(" + ec.message() + "): ").c_str());
};
Printing instead:
main #1: open
main #2: open
main #3: closed
handler(Success): closed
handler(Bad file descriptor): closed
Note that perhaps surprisingly, the first send operation still succeeded. Contrary to what I expected this indicates that the send is actually initiated right at the async_send_to
call, but the completion is delayed until after io.run()
(the socket is still shown to be already closed).
And maybe you did not want async operations at all:
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::udp;
int main() {
std::cout << std::boolalpha;
boost::asio::io_context io;
boost::asio::ip::udp::socket s {io, udp::v4()};
boost::asio::ip::udp::endpoint const ep {{}, 9999};
auto trace = [&s](char const* caption) { std::cout << caption << s.is_open() << std::endl; };
trace("main #1: ");
char buff[200] = {};
try {
/*size_t wlen =*/ s.send_to(boost::asio::buffer(buff), ep);
trace("sent #1: ");
} catch(boost::system::system_error const& e) {
std::cout << "Send #1 failed: " << e.code().message() << std::endl;
}
trace("main #2: ");
s.close();
try {
/*size_t wlen =*/ s.send_to(boost::asio::buffer(buff), ep);
trace("sent #2: ");
} catch(boost::system::system_error const& e) {
std::cout << "Send #2 failed: " << e.code().message() << std::endl;
}
trace("main #3: ");
s.close();
io.run();
}
Prints
main #1: true
sent #1: true
main #2: true
Send #2 failed: Bad file descriptor
main #3: false