Boost Asio async_read不会停止阅读吗? [英] Boost Asio async_read doesn't stop reading?
问题描述
所以
我一直在玩Boost asio函数和套接字(特别是异步读/写).现在,我以为boost::asio::async_read
仅在从网络连接传入新缓冲区时才调用处理程序...但是,它不会停止读取相同的缓冲区,因此会继续调用该处理程序.我已经能够通过检查传输的字节数来缓解这种情况,但是它基本上处于浪费CPU周期的繁忙循环中.
I've been playing around with the Boost asio functions and sockets (specifically the async read/write). Now, I thought that boost::asio::async_read
only called the handler when a new buffer came in from the network connection... however it doesn't stop reading the same buffer and thus keeps calling the handler. I've been able to mitigate it by checking the number of bytes transferred, however it is basically in a busy-waiting loop wasting CPU cycles.
这就是我所拥有的:
class tcp_connection : : public boost::enable_shared_from_this<tcp_connection>
{
public:
// other functions here
void start()
{
boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
const unsigned int TERRAINPACKETSIZE = 128;
char buf[TERRAINPACKETSIZE];
void handle_read(const boost::system::error_code& error, size_t bytesT)
{
if (bytesT > 0)
{
// Do the packet handling stuff here
}
boost::asio::async_read(socket_, boost::asio::buffer(buf, TERRAINPACKETSIZE),
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
};
一些东西被删除了,但是基本上创建了一个新的连接,然后调用了start()
.我缺少什么了,所以handle_read
方法不会被连续调用吗?
Some stuff is cut out, but basically a new connection gets created then start()
is called. Is there something I'm missing so that the handle_read
method doesn't get continuously called?
推荐答案
一个疯狂的猜测:您是否在handle_read
中选中error
?如果套接字由于某种原因处于错误状态,我猜想由handle_read
进行的对async_read
的嵌套调用将立即完成",从而导致对handle_read
A wild guess: Do you check error
in handle_read
? If the socket is in an error state for some reason, I guess that the nested call to async_read
made from handle_read
will immediately "complete", resulting in an immediate call to handle_read
这篇关于Boost Asio async_read不会停止阅读吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!