【发布时间】:2020-01-05 04:31:50
【问题描述】:
我正在尝试使用 Boost 1.60 中的 Asio 使用几个不同的示例编写 TCP 客户端。连接正常工作大约 30 秒左右,但断开并出现错误:
网络连接被本地系统中止
我尝试设置“ping/pong”设置以保持连接处于活动状态,但它仍然终止。我发现的唯一以前的 Stack Overflow 答案建议使用 Boost 的 shared_from_this 和一个共享指针,我已经调整了我的代码来使用。但问题依然存在。
设置 Connection 对象及其线程:
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()));
}
};
【问题讨论】:
-
你考虑过
deadline_定时器的效果吗,在start_read方法中设置为30秒? -
@kenba 不,我什至没有意识到读取有 30 秒的超时。当我将“ping”的代码更改为服务器时出现问题,因此它只发送一次,然后在服务器的初始响应之后 30 秒没有读取任何内容,因此它关闭了套接字。非常感谢!
-
@FranklinBarnett 请回答您自己的问题并接受它,以免它显示为未回答。
标签: c++ boost boost-asio shared-ptr