【发布时间】:2026-01-04 23:10:01
【问题描述】:
我一直在尝试使用 boost::asio 编写客户端-服务器应用程序,总体而言,该应用程序运行良好,但我偶然发现了一个问题,即当 connoction (在客户端 服务器之间)被防火墙丢弃或通过手动禁用新网络卡。
这里是sn-p的代码:
void write(const CommunicatorMessage & msg, std::function<void(bool)> writeCallback)
{
io_service.dispatch(
[this, msg, writeCallback]()
{
boost::asio::async_write(socket, boost::asio::buffer(msg.data(), msg.length()), [this, msg, writeCallback](boost::system::error_code ec, std::size_t length)
{
writeCallback(ec != 0);
if (!ec)
{
LOG_DEBUG("Number of bytes written into the buffer: " << length << " Error code: " << ec);
LOG_DEBUG("Successfully send msg: " << msg);
}
else
{
LOG_ERROR("Failed sending msg: " << msg);
throw std::exception(ec.message().c_str());
}
});
});
}
来自 Writehandler 的数据是有效的(错误代码为 0,bytes_transferred 是正确的),即使数据没有到达服务器。我已经用 Wireshark 跟踪了整个流程(这里有一个截图链接Link)
【问题讨论】:
-
一般来说,这种方式是检测不到网络断开的(阅读下面的帖子:lists.boost.org/boost-users/2009/07/50319.php)。您需要在应用程序中实现某种心跳。
标签: c++ boost handler boost-asio