我有ASIO增強庫的問題。問題是異步功能。ASIO庫 - 未調用的處理程序
這是簡單的服務器代碼。
void handle_accept(const boost::system::error_code& error)
{
std::cout << "Someone connected" << std::endl;
}
void handle_read(const boost::system::error_code& error)
{
printf("Message: %s \n", somedata);
}
int main()
{
std::cout << "Starting server ....\n" << std::endl;
try
{
boost::asio::io_service io_service;
tcp::socket mysocket(io_service);
tcp::acceptor myacceptor(io_service, tcp::endpoint(tcp::v4(), 5000));
myacceptor.async_accept(mysocket, boost::bind(&handle_accept, boost::asio::placeholders::error));
mysocket.async_receive( boost::asio::buffer(somedata, 1024) , boost::bind(&handle_read, boost::asio::placeholders::error));
io_service.run();
std::cout << "END. \n" << std::endl;
sleep(5);
} catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
這裏
int main()
{
std::cout << "Starting client ....\n" << std::endl;
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), "localhost", "5000");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket mysocket(io_service);
boost::asio::connect(mysocket, endpoint_iterator);
sleep(5);
sprintf(somedata, "This is a message i sent.");
mysocket.send(boost::asio::buffer(somedata, 1024) );
} catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
所以客戶端代碼,如何它應該工作。服務器應該等待來自客戶端的連接,當客戶端連接時,它應該調用handle_accept。當客戶端連接時,handle_accept真的被調用,但它也調用handle_read,即使沒有數據收到!爲什麼?客戶端在連接5秒後發送數據。
非常感謝。
您通常從'handle_accept'函數內開始接收/發送循環。檢查Asio [教程](http://www.boost.org/doc/html/boost_asio/tutorial.html)和[示例](http://www.boost.org/doc/html/boost_asio/examples。 HTML)。 – Xeo
您還需要檢查處理程序中的錯誤代碼,因爲處理程序已被調用的事實並不意味着它已成功。 –