Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio: How do I use async_accept to accept incoming connections?

I'm using boost::asio, and I have code like this:

void CServer::Start(int port)
{ 
    tcp::acceptor acceptor(m_IoService, tcp::endpoint(tcp::v4(), port));

    for ( ;; )
    {
        shared_ptr<tcp::socket> pSocket(new tcp::socket(m_IoService));

        acceptor.accept(*pSocket);

        HandleRequest(pSocket);
    }
}

This code works, but I'd like to switch to using Acceptor::async_accept so that I can call Acceptor::cancel to stop receiving requests.

So my new code looks like this:

void CServer::StartAsync(int port)
{ 
    m_pAcceptor = shared_ptr<tcp::acceptor>( new tcp::acceptor(m_IoService, tcp::endpoint(tcp::v4(), port)) );

    StartAccept();
}

void CServer::StopAsync()
{
    m_pAcceptor->cancel();
}

void CServer::StartAccept()
{
    shared_ptr<tcp::socket> pSocket(new tcp::socket(m_IoService));

    m_pAcceptor->async_accept(*pSocket, bind(&CServer::HandleAccept, this, pSocket));   
}

void CServer::HandleAccept(shared_ptr<tcp::socket> pSocket)
{
    HandleRequest(pSocket);

    StartAccept();
}

But this code doesn't seem to work, my function CServer::HandleAccept never gets called. Any ideas? I've looked at sample code, and the main difference between my code and theirs is they seem often make a class like tcp_connection that has the socket as a member, and I'm not seeing why thats necessary.

  • Alex
like image 737
Alex Black Avatar asked Jul 06 '09 14:07

Alex Black


1 Answers

Ah, looks like to kick things off you need to run the IOService, e.g.:

m_IoService.run();
like image 153
Alex Black Avatar answered Sep 30 '22 03:09

Alex Black