【问题标题】:boost read_until stops at white spaceboost read_until 在空白处停止
【发布时间】:2020-10-26 16:56:05
【问题描述】:

我正在尝试使用 boost 设置一个 tcp 套接字服务器。由于某种原因,函数read_until 似乎停止在空白处,而不是一直到分隔符。 例如:

发送

┼N▀]»ü rx}q╠Cä≥è┘Y\║ï2æ╨╬ΣfV╠παÇ/S┬0è3à ╫VR∞{εoÆ?LeN≡╬.lÖnÖ1⌡&âm&ù╫ä╛'°≈L▀_ °çF¿P»2ß|╪+96#3kα≥
╟¬─╣╩í▄¢hú╤fûº╢5~AcbF┌Zd╒∞?╓)a.ƒ¿B■αZº=■uΣ╔nÜ┌╬▌╝>┌iE┌y≈ÿ≤┴Kå ²å£∩¢R>╒S(y╙cPjA▀▀Z2O╓?  ÆÉ@τß╢ªy╗▒*Γ▓σ&K₧@╦╩∙⌠%ßΩ-x*Ü╞7ε_█zâ╡C
╧╩║╗Q■═TM╠<æ┤päi^▓'àiUóα<«3Çÿ ─╗E  Σ]ππa╒εk»╣╕(╔╡╙ä╝y≡╥¡╠▌╪┼¡Ö
a|MC├₧\y╚üßσ√⌡ÿ±2<æq}ÿ┌Mzçα∩òΣÆ{end}

收到:

┼N▀]»ü

我从套接字读取的代码是

string read_(tcp::socket& socket, CryptoPP::RSA::PrivateKey *privateKey) {
    boost::asio::streambuf buf;
    boost::asio::read_until(socket, buf, "{end}");
    string data = boost::asio::buffer_cast<const char*>(buf.data());
    std::cout << "recived:\n" << data << std::endl;
    return data
}

解决方案:

string read_(tcp::socket& socket, CryptoPP::RSA::PrivateKey *privateKey) {
    boost::asio::streambuf buf;
    boost::asio::read_until(socket, buf, "{end}");
    streambuf::const_buffers_type buf2 = buf.data();
    string data(buffers_begin(buf2), buffers_begin(buf2) + buf.size());
    std::cout << "recived:\n" << data << std::endl;
    return data
}

【问题讨论】:

  • 不要将二进制数据视为 c 字符串。 read_until 返回什么?
  • @tkausl 它返回一个const_buffers_1。如果我检查具有所有字符的调试器中的大小。所以,如果我的静态演员不起作用,你知道有一种方法可以得到所有角色吗?

标签: c++ tcp boost-asio


【解决方案1】:

您应该以安全的方式输出字符,例如通过将每个字节打印为 2 个十六进制数字:

auto read_(tcp::socket& socket, CryptoPP::RSA::PrivateKey * /*privateKey*/) {
    std::vector<uint8_t> data;
    boost::asio::read_until(
        socket,
        boost::asio::dynamic_buffer(data),
        "{end}");

    std::cout << "received:\n";
    for (int ch : data) {
        std::cout << " " << std::hex << std::setw(2) << std::setfill('0') << ch;
    }

    return data;
}

请注意,我选择:

  • 省略中间的streambuf
  • 借此机会证明您可以轻松使用更合适的数据结构 (std::vector&lt;uint8_t&gt;),当然您也可以将其替换为 std::string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2011-08-21
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多