简体   繁体   中英

boost::asio::async_read_until not calling handler

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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