开发者

Boost async_accept causes an 'access violation' - error

Server::Server(boost::asio::io_service& io_service,std::string ip,short port,std::shared_ptr<ConnectionFactory> factory)
    : acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(ip.data()), port)){

        m_factory = factory;
        start_accept();

        std::cout<<"Socket accepting connections..."<<std::endl;
}

void Server::start_accept(){
    boost::asio::io_service io_service;
    std::shared_ptr<Connection> conn = m_factory->create(io_service);

    acceptor_.async_accept(conn->socket(),
        boost::bind(&Server::handle_accept, this,conn,
          boost::asio::placeholders::error));

}


void Server::handle_accept(std::shared_ptr<Connection> conn,const boost::system::error_code& error)开发者_如何学运维{

    if (!error)
    {
        std::cout<<"on connected"<<std::endl;
        conn->OnConnected();
        start_accept();
    }
  }

When I run the project I get following error:

Access violation reading location 0xfeeeff02.

What is the cause of this error?


Your io_service is going out of scope in start_accept(), that is not good and likely not what you intend.

change this

Server::Server( ... ) {
        m_factory = factory;
        start_accept();

        std::cout<<"Socket accepting connections..."<<std::endl;
}

void Server::start_accept() {
    boost::asio::io_service io_service;
                        ^^^^^^^^^
    std::shared_ptr<Connection> conn = m_factory->create(io_service);

    acceptor_.async_accept(conn->socket(),
        boost::bind(&Server::handle_accept, this,conn,
          boost::asio::placeholders::error));

}

to this

Server::Server( ... ) {   
        m_factory = factory;
        start_accept( io_service );
                      ^^^^^^^^^

        std::cout<<"Socket accepting connections..."<<std::endl;
}

void Server::start_accept( const boost::asio::io_service& io_service ){
    std::shared_ptr<Connection> conn = m_factory->create(io_service);

    acceptor_.async_accept(conn->socket(),
        boost::bind(&Server::handle_accept, this,conn,
          boost::asio::placeholders::error));

}

Though, as your comments have suggested, you really should post a self-contained example of the problem. The above suggestion is my best guess.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜