[英]Boost::asio::async_read doesn't stop on condition
I have some issue with boost::asio::async_read 我对boost :: asio :: async_read有一些问题
Here's my code 这是我的代码
void TCPConnection::listenForRead() {
boost::asio::async_read(m_socket,
boost::asio::buffer(m_inbound_data),
boost::asio::transfer_at_least(64),
boost::bind(&TCPConnection::handle_read,
shared_from_this(),
boost::asio::placeholders::error)
);
}
And Here's the handler : 这是处理程序:
void TCPConnection::handle_read(const boost::system::error_code& error) {
if (error) {
std::cout << "Error read: " << error.category().name() << " -- " << error.value() << std::endl;
} else {
std::string archive_data(&m_inbound_data[0], m_inbound_data.size());
std::cout << "Message received: " << archive_data << std::endl;
listenForRead();
}
}
With 同
std::vector<char> m_inbound_data;
I get an infinite loop on the console when a client connect: 当客户端连接时,我在控制台上得到一个无限循环:
"Message received: " //no trace of message “收到消息:”//没有消息的痕迹
If i print the data length, it is always at 0. 如果我打印数据长度,它始终为0。
I connect with : telnet localhost 4242 我连接:telnet localhost 4242
Anyone know why ? 谁知道为什么? should it not wait for at least 64 char ?
它不应该等待至少64个字符?
Boost.Asio will never resize your buffer. Boost.Asio永远不会调整你的缓冲区大小。
When you create a buffer from an std::vector<char>
, the size of the buffer is the size of the vector. 从
std::vector<char>
创建缓冲区时,缓冲区的大小是向量的大小。
If you don't give it a size, it will be a zero-length buffer. 如果你没有给它一个大小,它将是一个零长度的缓冲区。
The transfer_at_least
functor returns true if either at least N bytes are in the buffer or the buffer is full. 如果缓冲区中至少有N个字节或缓冲区已满,则
transfer_at_least
仿函数返回true。 In the case of a zero length buffer, it's always full, so it always returns true. 在长度为零的缓冲区的情况下,它总是满的,所以它总是返回true。
To go along with dauphic's answer: 与dauphic的答案一致:
You may initialize a char array like you did: 你可以像你一样初始化一个char数组:
char data[64]
Or if you still want to use a vector you can initialize the vector to a certain size: 或者,如果您仍想使用矢量,则可以将矢量初始化为特定大小:
std::vector<char> data(64)
or
std::vector<char> data;
data.resize(64);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.