提高:: ASIO :: async_read_until没有要求处理程序(boost::asio:

2019-09-20 06:01发布

我正在学习如何使用升压:ASIO库串行端口。 我写了使用synchrous写一些代码和阅读,我现在想用asynchrous,但它不工作。 简单的例子:

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()。 如果我改变synchrous读,它的读取距离Port确定。 我还检查BUF对象的每个while循环,它是空的。 我做错了什么?

Answer 1:

作为Janm指出你需要调用io.run为async_read_until工作。

但...

您还需要写在转换为ASYNC_WRITE,作为同步和异步调用真的不在一起ASIO内工作。 什么,你需要做的是以下几点:

设置第一ASYNC_WRITE呼叫io.run

在写处理程序设置的async_read_until

在你读的处理程序设置下一个ASYNC_WRITE



Answer 2:

你需要调用io_service对象的回调上班run()方法。 在你的循环,你需要io.run()



文章来源: boost::asio::async_read_until not calling handler