来自 boost::asio::async_write 的 WriteHandler 在连接断开时无法正常工作(防火墙/手动断开网络)



我一直在尝试使用 boost::asio 编写客户端-服务器应用程序,总体而言,该应用程序运行良好,但我偶然发现了有关"WriteHandler"(async_write函数)提供的数据的问题,当连接(客户端<>服务器之间)被防火墙或手动禁用 newtwork 卡丢弃时。

以下是代码片段:

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 跟踪了整个流程(这是带有屏幕截图链接的链接)

async_write向您发送成功时,这意味着它已成功写入内核的缓冲区。但是,它不能保证数据包已交付。

最新更新