![](/img/trans.png)
[英]Boost asio “network connection was aborted by local system” on async_read_some
[英]How can I get around this “Network connection aborted by local system” using Boost Asio with a shared pointer?
我正在嘗試使用Boost 1.60中的Asio使用幾個不同的示例編寫TCP客戶端。 該連接可能在30秒左右的時間內正常工作,但由於錯誤而斷開連接:
網絡連接被本地系統中止
我嘗試設置“乒乓”設置以保持連接有效,但仍會終止。 我發現的僅有的以前的堆棧溢出答案建議使用Boost的shared_from_this和共享指針,我已對代碼進行了調整。 但是問題仍然存在。
設置連接對象及其線程:
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver res(ios);
boost::shared_ptr<Connection> conn = boost::shared_ptr<Connection>(new Connection(ios));
conn->Start(res.resolve(boost::asio::ip::tcp::resolver::query("myserver", "10635")));
boost::thread t(boost::bind(&boost::asio::io_service::run, &ios));
這是Connection類的相關部分(我也確保在其他所有地方也使用shared_from_this()):
class Connection : public boost::enable_shared_from_this<Connection>
{
public:
Connection(boost::asio::io_service &io_service)
: stopped_(false),
socket_(io_service),
deadline_(io_service),
heartbeat_timer_(io_service)
{
}
void Start(tcp::resolver::iterator endpoint_iter)
{
start_connect(endpoint_iter);
deadline_.async_wait(boost::bind(&Connection::check_deadline, shared_from_this()));
}
private:
void start_read()
{
deadline_.expires_from_now(boost::posix_time::seconds(30));
boost::asio::async_read_until(socket_, input_buffer_, 0x1f,
boost::bind(&Connection::handle_read, shared_from_this(), _1));
}
void handle_read(const boost::system::error_code& ec)
{
if (stopped_)
return;
if (!ec)
{
std::string line;
std::istream is(&input_buffer_);
std::getline(is, line);
if (!line.empty())
{
std::cout << "Received: " << line << "\n";
}
start_read();
}
else
{
// THIS IS WHERE THE ERROR IS LOGGED
std::cout << "Error on receive: " << ec.message() << "\n";
Stop();
}
}
void check_deadline()
{
if (stopped_)
return;
if (deadline_.expires_at() <= deadline_timer::traits_type::now())
{
socket_.close();
deadline_.expires_at(boost::posix_time::pos_infin);
}
deadline_.async_wait(boost::bind(&Connection::check_deadline, shared_from_this()));
}
};
問題出在服務器端。 服務器沒有正確發送“ pong”響應到客戶端的ping,因此async_read_until()調用從未完成,因此也從未重置最后期限計時器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.