c++ - boost::asio::async_write 混合来自两条消息的数据(错误)

标签 c++ asynchronous client-server boost-asio

<分区>

我将 boost::asio 用于异步客户端和服务器。 在工作过程中,客户端向服务器发送不同类型的数据:小型服务消息(5-50 B)和带有原始图像数据的最大消息(40-200 KB)。 当我按顺序调用 Client::send 时(在一个线程中,连续):

  1. 发送“小服务消息”;
  2. 发送“大图消息”;

我在服务器湖上得到混合数据(错误):

|大消息开始||小消息||大消息结束|

void Client::send(MessageType type, const void* data, int size, bool read_header_after) {
    assert(cstatus.is_connected());

    header.type = type;
    size_t buf_size = sizeof(ProtocolHeader) + size;
    Bytes *p = new Bytes();
    p->resize(buf_size);
    std::memcpy(&p->front(), &header, sizeof(ProtocolHeader));
    if (size) {
        std::memcpy(&p->at(sizeof(ProtocolHeader)), data, size);
    }


    std::cout << "***** SEND start: " << p->size() << " bytes *****" << std::endl;


    ba::async_write(*socket, ba::buffer(&p->front(), buf_size),
                    ba::transfer_exactly(buf_size),
                    [this, p, read_header_after](const boost::system::error_code& ec, std::size_t length) {

        std::cout << "***** SEND complete: "
                  << p->size() << " bytes; ec="
                  << ec.value() << " (" << ec.message() << ") bufsize="
                  << p->size()
                  << " *****"
                  << std::endl;

        size_t buf_size = p->size();
        delete p; // remove sent data

        if (ec) {
            cstatus.set_last_network_error("Client::send " + ec.message());
            connection_failed("send - ec");
        } else if (length < buf_size) {
            connection_failed("send - len");
        } else {
            if (read_header_after) {
                read_header();
            }
            start_check_timer(NORMAL_INTERVAL_DATA_SEND_MILLISEC);
        }
    });
}

输出显示小消息作为第二个发送到 async_write 但在大消息之前作为第一个执行(完成)。

***** SEND start: 53147 bytes *****
***** SEND start: 5 bytes *****
***** SEND complete: 5 bytes; ec=0 (Success) bufsize=5 *****
***** SEND complete: 53147 bytes; ec=0 (Success) bufsize=53147 *****

这怎么可能以及如何同步?谢谢!

更新

我不需要同步任务队列。我需要同步两个具有不同缓冲区大小的 async_write 操作。

最佳答案

这不是错误。文档 ( http://www.boost.org/doc/libs/1_62_0/doc/html/boost_asio/reference/async_write/overload1.html ) 明确表示,除非有另一个正在进行,否则不应在同一套接字上执行其他写操作。 这是因为 async_write 在对 async_write_some 的多次调用中被翻译。 如果您在同一个线程上,我的建议是使用写入队列,在其中添加要发送的数据,然后在写入回调中提取它以执行另一个操作。

关于c++ - boost::asio::async_write 混合来自两条消息的数据(错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40376024/

相关文章:

c++ - 头文件在整个程序中只包含一次?

c++ - 返回类的私有(private)静态成员

c# - C# 中的线程和异步操作

design-patterns - 软件架构、并行处理和异步模式

client-server - 如何从客户端脚本中的空闲端口启动服务器?

java - 为什么服务器没有收到客户端发送的对象?

c++ - 在 C/C++ 源代码中验证格式字符串的工具

c++ - 假设的、以前的 C++0x 概念问题

mysql - 与 NodeJs 同时运行 Mysql 查询

client-server - 示例开源客户端 - 服务器代码项目