async_read 和 async_read_some 的区别

Start an asynchronous operation to read a certain amount of data from a stream.

template<
    typename AsyncReadStream,
    typename MutableBufferSequence,
    typename ReadHandler>
void async_read(
    AsyncReadStream & s,
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.


Start an asynchronous read.

template<
    typename MutableBufferSequence,
    typename ReadHandler>
void async_read_some(
    const MutableBufferSequence & buffers,
    ReadHandler handler);

This function is used to asynchronously read data from the stream socket. The function call always returns immediately.


总结一下:
      asio::async_read 通常用户读取指定长度的数据,读完或出错才返回。
      而socket的async_read_some读取到数据或出错就返回,不一定读完了整个包。 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 `async_read_some` 函数时,由于串口接收数据的速度往往快于程序处理数据的速度,因此可能会出现一次读取无法全部读取串口数据的情况。 为了避免这种情况,可以采用循环异步读取的方式,即在回调函数中再次调用 `async_read_some` 函数。例如: ```cpp void read_handler(const boost::system::error_code& error, std::size_t bytes_transferred, boost::asio::serial_port& port, char* data, std::size_t size) { if (!error) { // 处理接收到的数据 // 继续异步读取数据 boost::asio::async_read_some(port, boost::asio::buffer(data, size), boost::bind(read_handler, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(port), data, size)); } else { // 读取出错 } } int main() { boost::asio::io_service io; boost::asio::serial_port port(io, "/dev/ttyUSB0"); char data[1024]; // 异步读取数据 boost::asio::async_read_some(port, boost::asio::buffer(data, 1024), boost::bind(read_handler, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, boost::ref(port), data, 1024)); io.run(); return 0; } ``` 上述代码中,我们定义了一个 `read_handler` 函数,用于处理接收到的数据。在回调函数中,如果数据没有读取完全,就继续调用 `async_read_some` 函数读取剩余的数据,直到全部数据都被读取完毕。 需要注意的是,在使用循环异步读取数据的方式时,需要避免出现死循环或者阻塞程序的情况。可以设置一个最大读取次数或者最长等待时间,如果达到了限制条件仍然没有读取完全部数据,就退出循环。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值