gpt4 book ai didi

c++ - 为什么这个简单的服务器不接受连接?

转载 作者:行者123 更新时间:2023-11-30 02:56:22 26 4
gpt4 key购买 nike

我刚开始使用 boost asio 并操作了我在网上找到的一个简单服务器的代码片段。这是代码

void OnAccept( const boost::system::error_code & ec, boost::shared_ptr< boost::asio::ip::tcp::socket > sock )
{
if( ec )
{
std::cout << "[" << boost::this_thread::get_id()<< "] Error: " << ec << std::endl;
}
else
{
std::cout << "[" << boost::this_thread::get_id()<< "] Accepted!" << std::endl;
}
}

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";
while(true)
{
Sleep(400);
}
}
catch( std::exception & ex )
{
std::cout << "[" << boost::this_thread::get_id()<< "] Exception: " << ex.what() << std::endl;
}
}


int main( int argc, char * argv[] )
{
boost::thread server(RunServer);
std::cout << "Press any key to stop..\n";
std::cin.get();
return 0;
}

不幸的是,代码不接受连接。我试过 telnet localhost 7777 但它不接受任何建议的连接?

最佳答案

您正在启动一个异步接受,但您不允许 io_service 运行。您需要执行同步接受或调用调用 io_service->run()。相关部分将变为:

    std::cout << "Waiting for incoming connections \n";
io_service->run();
}

我建议你比较Daytime.2 - A synchronous TCP daytime serverDaytime.3 - An asynchronous TCP daytime server

关于c++ - 为什么这个简单的服务器不接受连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com