boost::asio::async_read_until not calling handler

 ̄綄美尐妖づ 提交于 2020-02-03 02:00:59

问题


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() 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 ??


回答1:


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

But...

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:

setup first async_write call io.run

in your write handler setup the async_read_until

in your read handler setup the next async_write




回答2:


You need to call the run() method on the io_service for the callbacks to work. In your loop, you need io.run().



来源:https://stackoverflow.com/questions/11670014/boostasioasync-read-until-not-calling-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!