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