简体   繁体   中英

Boost.Asio UDP async_read_from segmentation fault

I'm building an asynchronous UDP socket and managing it with timer using boost. The second time I try to read data from the socket using socket.async_read_from, I'm getting a segmentation fault. (Using netbeans and the debugger doesn't seem to do anything...). The first time I read works well. Netbeans just throws some assembly code. I can't even make a break point work. Is there something I'm missing? I checked the address of every objects sent to async_read_from and everything seem legit... The first call to readData() works well, so I'm guessing it has something to do with the io_service?

bool ServerInstance::openServer()
{
try{
    io_service io_service;
    this->endpoint_= new ip::udp::endpoint(ip::udp::v4(),nPortNumber_);
    this->socket_ = new ip::udp::socket(io_service, *(this->endpoint_));
  //  this->socket_->non_blocking(false);
    this->readData();

}catch(std::exception &e)
{
    this->strErrorMsg_ = e.what();
    return false;
}

return true;

}
char* readData()
{boost::array<char,80> buf;
boost::system::error_code ec = boost::asio::error::would_block;

this->startTimer();

socket_->async_receive_from(buffer(buf),*(this->endpoint_),
        boost::bind(&ServerInstance::handle_read,_1,&ec));

while(ec == boost::asio::error::would_block)
{
    socket_->get_io_service().run_one();
}
this->stopTimer();
socket_->get_io_service().reset();
return buf.data();
}

When the socket is created, I thought the io_service object would be copied but alas no. Since it was declared locally, it is destroyed after the establishConnection() method completes. Declared it as a global pointer and it's working great now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM