boost :: asio接受套接字错误已经打开

时间:2013-09-12 18:29:33

标签: c++ sockets boost asynchronous boost-asio

我不确定导致此错误的原因Already Open

#include "AsyncServer.h"


AsyncServer::AsyncServer(boost::asio::io_service& io_service, std::string ip, unsigned short port)
    : acceptor(io_service, tcp::endpoint(boost::asio::ip::address_v4::from_string(ip), port))
{

    BeginAccept();
}


AsyncServer::~AsyncServer()
{
}


void AsyncServer::BeginAccept(){
    tcp::socket temp = tcp::socket(acceptor.get_io_service());
    acceptor.async_accept(temp, boost::bind(&AsyncServer::EndAccept, this, boost::asio::placeholders::error));
}

void AsyncServer::EndAccept(const boost::system::error_code& error){

    if (!error)
    {
        //continue with connection
        std::cout << "connected" << std::endl;
    }
    else
    {
        std::cout << error.message() <<std::endl;
    }

    BeginAccept();
}

我要做的是将套接字和错误传递给EndAccept,但它会中断,错误是Already Open,我不知道这里有什么问题!

1 个答案:

答案 0 :(得分:4)

temp是一个本地对象,它会在BeginAccept出口处立即被销毁。这意味着async_accept使用悬挂引用,这是未定义的行为。

temp成为会员(给它更有意义的名字也是个好主意。)