![](/img/trans.png)
[英]when is the handler for boost::asio::async_read_until invoked?
[英]boost::asio::async_read_until not calling handler
我正在學習如何通過串行端口使用Boost:asio庫。 我使用同步寫和讀編寫了一些代碼,現在我想使用異步,但是它不起作用。 簡單的例子:
void readHandler(const boost::system::error_code&,std::size_t);
streambuf buf;
int main(int argc,char *argv[]){
io_service io;
serial_port port(io,PORT);
if(port.isopen()){
while(1){
// ... getting std::string::toSend from user ...
write(port,buffer(toSend.c_str(),toSend.size()));
async_read_until(port,buf,'\n',readHandler); // <= it's returning but not calling readHandler at all
}
port.close();
}
}
void readHandler(const boost::system::error_code& error,std::size_t bytes_transferred){
std::cout << "readHandler()" << std::endl;
//... reading from buf object and calling buf.consume(buf.size()) ...
}
async_read_until()返回但不調用readHandler() 。 如果更改為同步讀取,則表示從端口OK讀取。 我還在每個while循環中檢查buf對象,它是空的。 我做錯了什么?
您需要在io_service上調用run()方法,以使回調起作用。 在循環中,您需要io.run()
。
正如Janm指出的那樣,您需要調用io.run來使async_read_until起作用。
但...
您還需要將寫入轉換為async_write,因為sync和async調用在asio中不能很好地協同工作。 您需要執行以下操作:
設置第一個async_write調用io.run
在您的寫處理程序設置中async_read_until
在您的讀取處理程序設置中,下一個async_write
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.