1
我的程序充当客户端可以连接的服务器。一旦连接了一个客户端,他将每5秒钟从服务器获取更新。这是write
-function是每5秒被称为新的数据发送到客户端:Boost.Asio:异步操作超时
void NIUserSession::write(std::string &message_orig)
{
std::cout << "Writing message" << std::endl;
std::shared_ptr<std::string> message = std::make_shared<std::string>(message_orig);
message->append("<EOF>");
boost::system::error_code ec;
boost::asio::async_write(this->socket_, boost::asio::buffer(*message),
boost::asio::transfer_all(), boost::bind(&NIUserSession::writeHandler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred(),
message
));
}
void NIUserSession::writeHandler(const boost::system::error_code &error, std::size_t bytes_transferred, std::shared_ptr<std::string> message)
{
std::cout << "Write Handler" << std::endl;
if(error)
{
std::cout << "Write handler error: " << error.message() << std::endl;
this->disconnect();
}
}
void NIUserSession::disconnect()
{
std::cout << "Disconnecting client, cancling all write and read operations." << std::endl;
this->socket_.lowest_layer().cancel();
delete this;
}
如果在写操作的错误在服务器和客户端之间的连接被关闭,所有异步操作是cancled(this->socket_.lowest_layer().cancel();
)。如果连接超时,将不会立即调用writeHandler
。相反,写入操作“叠加”直到第一个到达writeHandler
。
这应该是程序的正常输出:
Writing message
Write Handler
... Other stuff ...
... Other stuff ...
Writing message
Write Handler
如果连接超时,这是发生了什么:
Writing message
Write Handler
Write handler error: Connection timed out
Disconnecting client, cancling all write and read operations.
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Write Handler
Segmentation fault
最后,分段错误上升。我认为这是因为disconnect
被调用,而其他异步操作仍在进行中。 我想我可以通过在第一次异步操作失败后直接使用this->socket_.lowest_layer().cancel();
来避免它,但它不起作用。
如何避免分段错误?
它不会导致分段错误。它会导致[未定义行为](https://en.wikipedia.org/wiki/Undefined_behavior)。否则,+1 – sehe
使用异步操作时,您需要非常小心对象的生命周期。 'boost :: asio' [示例](http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/examples/cpp11_examples.html)使用'shared_ptr'有很好的理由,参见:[启动asio异步功能和共享ptrs](http://stackoverflow.com/questions/11356742/boost-async-functions-and-shared-ptrs/19622084#19622084) – kenba
@sehe - 谢谢,编辑:)我不好使用不正确的措辞。 –