如果可能,最好的方法是使用多个线程。以下是我制作的一段类似的代码,本质上与您想要的类似。
void Session::handle_read(const boost::system::error_code& error, size_t bytes_transferred)
{
static int count = 0;
std::cout << "reading..." << std::endl;
//std::string sClientIp = socket().remote_endpoint().address().to_string();
if (!error)
{
// This is one place where you can put your thread call.
try
{
// Will have async_read_some reading on the socket and call handle_read when something is transfered
socket_.async_read_some(boost::asio::buffer(dataRx, max_length),
boost::bind(&Session::handle_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
catch(std::exception& e)
{
std::cout << "Read some failed: " << e << std::endl;
}
}
else if(error == boost::asio::error::eof)
{
std::cout << "There was an error in handle_read" << std::endl;
delete this;
}
else
{
std::cout << "some error" << std::endl;
}
}
在handle_read 内部,您需要一种方法来创建一个处理数据的线程,该线程将独立于主线程运行。如果对如何处理有任何困惑,请告诉我。