Boost.Asio UDP async_read_from 分段错误
我正在构建一个异步 UDP 套接字并使用 boost 通过计时器对其进行管理。第二次我尝试使用 socket.async_read_from 从套接字读取数据时,出现分段错误。 (使用netbeans和调试器似乎没有做任何事情......)。我第一次读的时候效果很好。 Netbeans 只是抛出一些汇编代码。我什至无法使断点起作用。我有什么遗漏的吗?我检查了发送到 async_read_from 的每个对象的地址,一切似乎都是合法的...第一次调用 readData() 效果很好,所以我猜测它与 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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建套接字时,我认为 io_service 对象会被复制,但可惜没有。由于它是在本地声明的,因此它会在
assessmentConnection()
方法完成后被销毁。将其声明为全局指针,现在运行良好。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 theestablishConnection()
method completes. Declared it as a global pointer and it's working great now.