0

我正在学习如何将 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对象,它是空的。我做错了什么??

4

2 回答 2

0

您需要调用 io_service 上的 run() 方法才能使回调起作用。在您的循环中,您需要io.run().

于 2012-07-26T13:11:50.623 回答
0

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

但...

您还需要将写入转换为 async_write,因为同步和异步调用在 asio 中不能很好地协同工作。您需要做的是:

设置第一个 async_write 调用 io.run

在您的写处理程序设置 async_read_until

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

于 2012-07-26T13:28:32.033 回答