boost :: asio :: async_read_until不调用处理程序 [英] boost::asio::async_read_until not calling handler

查看:193
本文介绍了boost :: asio :: async_read_until不调用处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何将Boost:asio库与串行端口一起使用.我使用同步写和读编写了一些代码,现在我想使用异步,但是它不起作用. 简单的例子:

I'm learning how to use Boost:asio library with Serial Port. I wrote some code using synchrous write and read and I now want to use asynchrous but it's not working. Simple Example:

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 对象,该对象为空.我在做什么错了?

async_read_until() it's returning but not calling readHandler(). If I change to synchrous read, it's reading from port OK. I also checking buf object each while loop and it's empty. What I'm doing wrong ??

推荐答案

正如Janm指出的那样,您需要调用io.run才能使async_read_until正常工作.

As Janm has pointed out you need to call io.run for the async_read_until to work.

但是...

您还需要将写入转换为async_write,因为sync和async调用在asio中不能很好地协同工作.您需要执行的操作如下:

You also need to convert the write over to an async_write, as the sync and async calls don't really work well together within asio. What you would need to do is the following:

设置第一个async_write 致电io.run

setup first async_write call io.run

在写处理程序中设置async_read_until

in your write handler setup the async_read_until

在读取处理程序中设置下一个async_write

in your read handler setup the next async_write

这篇关于boost :: asio :: async_read_until不调用处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆