当涉及到 TCP/IP 套接字时,我很难理解 io_service 的作用。这是我对io_service的基本理解。io_service->run()
阻止并接受工作请求(我们使用)io_service::work
或post
工作dispatch
到io_service
. 我在这里正确吗?如果我遗漏了什么,请告诉我?现在以下是我的简单服务器代码
void RunServer()
{
boost::shared_ptr< boost::asio::io_service > io_service(new boost::asio::io_service);
boost::shared_ptr< boost::asio::ip::tcp::acceptor > acceptor(new boost::asio::ip::tcp::acceptor( *io_service ));
boost::shared_ptr< boost::asio::ip::tcp::socket > sock( new boost::asio::ip::tcp::socket( *io_service ) );
try
{
boost::asio::ip::tcp::resolver resolver( *io_service );
boost::asio::ip::tcp::resolver::query query( "127.0.0.1", boost::lexical_cast< std::string >( 7777 ));
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve( query );
acceptor->open( endpoint.protocol() );
acceptor->set_option( boost::asio::ip::tcp::acceptor::reuse_address( false ) );
acceptor->bind( endpoint );
acceptor->listen( boost::asio::socket_base::max_connections );
acceptor->async_accept( *sock, boost::bind( OnAccept, _1, sock ) );//Receives only one connection
std::cout << "Waiting for incoming connections \n";
io_service->run(); //Confusion here --- Line A
}
catch( std::exception & ex )
{
std::cout << "[" << boost::this_thread::get_id()<< "] Exception: " << ex.what() << std::endl;
}
}
现在我知道如果 io_service 没有附加工作对象,该方法io_service->run()
将永远不会阻塞,对吗?现在我的问题是上面扮演了什么角色io_service->run()
。从实验中我意识到,如果我删除代码,OnAccept
则不会调用该方法。还有工作在哪里被添加到io_service
这里。这里到底发生了什么?任何澄清这一点的解释将不胜感激。