How do pass arguments to boost asio async_accept

2.3k views Asked by At

I have one problem.

I'm developing chat server, using boost::asio.

and Here,

void CServerSocket::StartAccept(boost::asio::ip::tcp::acceptor &acceptor)
{
    std::shared_ptr<boost::asio::ip::tcp::socket> socket(new boost::asio::ip::tcp::socket(acceptor.get_io_service()));

    acceptor.async_accept(*socket, std::bind(&CServerSocket::OnAccept, boost::asio::placeholders::error, socket,
        std::ref(acceptor)));
}

void CServerSocket::OnAccept(const boost::system::error_code &error, std::shared_ptr<boost::asio::ip::tcp::socket> socket, 
    boost::asio::ip::tcp::acceptor &acceptor)
{
    if (error)
    {
        CLogManager::WriteLog((boost::format("Accept error! : %1%") % error.message()).str().c_str());
        return;
    }

    m_SocketList.push_back(std::make_shared<CConnectionSocket>(this, socket));

    StartAccept(acceptor);
}

At std::bind, there are an error occurred.

"Error c2064 term does not evaluate to a function taking 3 arguments"

What should i do?

thanks.

2

There are 2 answers

0
Igor R. On

If you're using std::bind, replace boost::asio::placeholders::error with std::placeholders::_1.

3
kenba On

An accept handler may only take an error code as a parameter, see: AcceptHandler.

I recommend making acceptor a member of CServerSocket then changing the call to async_accept to:

acceptor.async_accept(*socket, std::bind(&CServerSocket::OnAccept, this,
                                         std::placeholders::_1));

and accessing acceptor within the OnAccept member function.