run code bellow,case2 failed
but if comment out the case 1 code,the case 2 code:
socket.async_connect(endpoint, std::bind(handle_connect, std::placeholders::_1, endpoint));
works fine.
what make these two seem have conflict??? seems when actual running case 2 code the io_service has stopped
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
using ip::tcp;
void handle_connect(const boost::system::error_code& error, const tcp::endpoint& endpoint) {
if (!error) {
std::cout << "socket.async_connect Connected successfully!" << std::endl;
}
else {
std::cout << "socket.async_connect Error ... " << error.message() << std::endl;
}
}
int main() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::io_service::work wr(io_service);
boost::asio::steady_timer timer(io_service);
auto m_resolver = boost::asio::ip::tcp::resolver(io_service);
boost::asio::ip::tcp::resolver::query query("www.baidu.com", "80");
tcp::resolver::results_type results = m_resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("240e:ff:e020:966:0:ff:b042:f296"), 80);
io_service.post([&wr, &timer]() {
std::cout << "sleep 3 seconds then stop io service..." << std::endl;
timer.expires_from_now(std::chrono::seconds(3));
timer.async_wait([&wr](const boost::system::error_code& error) {wr.get_io_context().stop(); });
}
);
// case 1:this works , but if comment this, the case 2 works.
io_service.post([&socket, &results]() {
boost::asio::async_connect(socket, results, [](const boost::system::error_code& error, const tcp::endpoint& endpoint) {
if (!error) {
std::cout << "io_service post job Connected successfully!!!!!" << std::endl;
}
else {
std::cout << "Error during connection: " << error.message() << std::endl;
}
});
});
std::cout << "io_service begin.." << std::endl;
// case 2: why this fail!!
socket.async_connect(endpoint, std::bind(handle_connect, std::placeholders::_1, endpoint));
io_service.run();
std::cout << "io_service end.." << std::endl;
char a = getchar();
return 0;
}
run code bellow,case2 failed but if comment out the case 1 code,the case 2 code: socket.async_connect(endpoint, std::bind(handle_connect, std::placeholders::_1, endpoint)); works fine. what make these two seem have conflict??? seems when actual running case 2 code the io_service has stopped