2011-04-22 100 views

回答

0

如果我理解你的問題正確看來你是有正在通過接受套接字連接的處理方法來處理傳輸,這樣的問題接受者可以被釋放以獲得新的連接。在您接受連接後,您(顯然)需要處理遇到的連接。因此,建立一個接受方法,在建立連接後接受連接,創建一個新的處理類並將它傳遞給io_service的引用和連接進來的套接字,允許該類處理該連接的傳輸並受體方法等待更多連接(並沖洗並重復)。處理方法將特定於您的應用程序。

2

打開接受器後,將其綁定到端點,此端點就是您正在接受的端點,並且它(或者說與其關聯的套接字)被重用。您傳遞給async_accept的套接字引用是一個新的套接字,它將保存下一個傳入連接。

E.g.在HTTP Server升壓ASIO例如:

server::server(const std::string& address, const std::string& port, 
    const std::string& doc_root) 
    : io_service_(), 
    acceptor_(io_service_), 
    connection_manager_(), 
    new_connection_(new connection(io_service_, 
      connection_manager_, request_handler_)), 
    request_handler_(doc_root) 
{ 
    // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). 
    boost::asio::ip::tcp::resolver resolver(io_service_); 
    boost::asio::ip::tcp::resolver::query query(address, port); 
    boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); 
    acceptor_.open(endpoint.protocol()); 
    acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); 
    acceptor_.bind(endpoint); 
    acceptor_.listen(); 
    acceptor_.async_accept(new_connection_->socket(), 
     boost::bind(&server::handle_accept, this, 
     boost::asio::placeholders::error)); 
} 

每async_accept創建的new_connection對象具有一個新的套接字接收傳入的連接。接受方在內部保留一個套接字,用於接受與您通過它的端點關聯的套接字。

如果你看看handle_accept:

void server::handle_accept(const boost::system::error_code& e) 
{ 
    if (!e) 
    { 
    connection_manager_.start(new_connection_); 
    new_connection_.reset(new connection(io_service_, 
      connection_manager_, request_handler_)); 
    acceptor_.async_accept(new_connection_->socket(), 
     boost::bind(&server::handle_accept, this, 
      boost::asio::placeholders::error)); 
    } 
} 

你可以看到一個新的連接對象被創建(並在它的新的socket)舉行下傳入的連接。 new_connection _-> socket()返回對該套接字的引用。接受者仍然接受最初傳遞給它的相同套接字或端口。

相關問題