繁体   English   中英

boost :: asio :: async_read_until不调用处理程序

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM