我使用boost::asio异步客户端和服务器。在工作过程中,客户端向服务器发送不同类型的数据:小的业务消息(5- 50b),大的消息(40- 200kb),带有原始图像数据。当我依次调用Client::send时(在一个线程中,依次):
- 发送"小服务消息";
- 发送"大图消息";
我在服务器湖上得到混合数据(错误):
|大消息开始||小消息||大消息结束|
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操作与不同的缓冲区大小。
这不是一个bug。文档(http://www.boost.org/doc/libs/1_62_0/doc/html/boost_asio/reference/async_write/overload1.html)明确指出,在同一个套接字上执行其他写操作之前,不应该执行其他写操作。这是因为async_write
在对async_write_some
的多次调用中被转换。如果你在同一个线程上,我的建议是使用一个写队列,在其中添加要发送的数据,然后在写回调中提取它以执行另一个操作。