【问题标题】:boost::asio performant serial read (RS232)boost::asio 高性能串行读取 (RS232)
【发布时间】:2013-09-24 13:11:26
【问题描述】:

我有以下方法(位于类中)取自:https://gitorious.org/serial-port/serial-port/source/03e161e0b788d593773b33006e01333946aa7e13:1_simple/SimpleSerial.h#L46

        boost::asio::serial_port serial;
        // [...]

        std::string readLine() {
        char c;
        std::string result;
        while(true) {

            asio::read(serial,asio::buffer(&c,1));
            switch(c)
            {
                case '\r':
                    result+=c;
                    break;
                case '\n':
                    result+=c;
                    return result;
                default:
                    result+=c;
            }
        }

        return result;
      }

正如它所写的那样,“代码是为简单而优化的,而不是速度”。所以我正在考虑优化这段代码。但是我没有得到任何有用的结果。我的一般做法是这样的:

    void readUntil(const std::string& delim) {
        using namespace boost;

        asio::streambuf bf;
        size_t recBytes = asio::read_until(serial, bf, boost::regex(delim));
        [...]

'delim' 将是“\n”。但我不知道如何将 asio::streambuf 转换为 std::string。此外,我不知道这种方法是否会丢失字符。例如。如果我一次收到以下文本块:

 xxxxx\r\nyyyyyyy

我会不会只阅读 'xxxxx\r\n' 而其余的都丢失了?

【问题讨论】:

    标签: c++ boost serial-port boost-asio


    【解决方案1】:
    1. 你可以在asio::streambufdirectly中访问the data,像这样:const unsigned char *data = asio::buffer_cast<const unsigned char*> (yourBuff.data());
    2. 终结符后面的数据不会丢失,而是read_untilmay read it进入缓冲区。

    (请注意,以上所有内容都记录在 Asio 参考、教程和示例中。)

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多