ASIO库 - 未调用的处理程序

时间:2012-09-20 20:55:42

标签: c++ unix boost boost-asio

我遇到了ASIO boost库的问题。问题是异步函数。

这是简单的服务器代码。

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秒后发送数据。

非常感谢你。

1 个答案:

答案 0 :(得分:4)

接收立即完成,因为它无法等待,因为它没有什么可以等待的。 TCP侦听套接字上不会收到任何数据。仅在已连接的套接字上调用async_receive