gpt4 book ai didi

c++ - boost::asio::async_read_until 不调用处理程序

转载 作者:太空宇宙 更新时间:2023-11-04 04:22:53 27 4
gpt4 key购买 nike

我正在学习如何将 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()。如果我更改为同步读取,则它可以从端口读取。我还在每个 while 循环中检查 buf 对象,它是空的。我做错了什么??

最佳答案

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

但是...

您还需要将写入转换为 async_write,因为同步和异步调用在 asio 中并不能很好地协同工作。您需要执行以下操作:

设置第一个async_write调用 io.run

在你的写处理程序中设置 async_read_until

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

关于c++ - boost::asio::async_read_until 不调用处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com