我正在從 c 中的 asio 套接字讀取資料。
我需要將傳入的資料決議為 json。為此,我需要獲取單個 json 字串條目。我正在添加一個字符';' 在 json 字串的末尾,現在我需要在讀取時拆分該字符。我正在嘗試這個:
int main()
{
asio::io_service service;
asio::ip::tcp::endpoint endpoint(asio::ip::address::from_string("127.0.0.1"), 4444);
asio::ip::tcp::socket socket(service);
std::cout << "[Client] Connecting to server..." << std::endl;
socket.connect(endpoint);
std::cout << "[Client] Connection successful" << std::endl;
while (true)
{
std::string str;
str.resize(2048);
asio::read(socket, asio::buffer(str));
std::string parsed;
std::stringstream input_stringstream(str);
if (std::getline(input_stringstream, parsed, ';'))
{
std::cout << parsed << std::endl;
std::cout<<std::endl;
}
}
}
但它給了我字串的隨機部分。
完整的訊息是:(用于測驗,不是 json 格式)
this is the message in full, no more no less ;
我得到:
full, no more no less
this is the message in full, no more no less
ull, no more no less
is is the message in full, no more no less
l, no more no less
is the message in full, no more no less
no more no less
我在哪里錯了?
謝謝!
uj5u.com熱心網友回復:
我會使用read_until:
#include <boost/asio.hpp>
#include <iostream>
#include <iomanip>
namespace asio = boost::asio;
using asio::ip::tcp;
int main()
{
asio::io_service service;
tcp::socket socket(service);
socket.connect({{}, 4444});
std::string str;
while (auto n = asio::read_until(socket, asio::dynamic_buffer(str), ';')) {
std::cout << std::quoted(std::string_view(str).substr(0, n - 1)) << std::endl;
str.erase(0, n);
}
}
例如,使用示例服務器:
paste -sd\; /etc/dictionaries-common/words | netcat -l -p 4444
輸出是:
"A"
"A's"
"AMD"
"AMD's"
"AOL"
"AOL's"
"Aachen"
"Aachen's"
"Aaliyah"
"Aaliyah's"
"Aaron"
"Aaron's"
"Abbas"
"Abbas's"
"Aberdeen's"
...
"zucchinis"
"zwieback"
"zwieback's"
"zygote"
"zygote's"
"zygotes"
"?ngstr?m"
"?ngstr?m's"
"éclair"
"éclair's"
"éclairs"
"éclat"
"éclat's"
"élan"
"élan's"
"émigré"
"émigré's"
"émigrés"
"épée"
"épée's"
"épées"
"étude"
"étude's"
附加提示
您可以使用任何動態緩沖區。這是streambuf:
for (asio::streambuf buf; auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
或者,混合,顯示該dynamic_string_buffer模型與以下概念相同streambuf:
std::string str;
for (auto buf = asio::dynamic_buffer(str);
auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
或者還有:
std::vector<unsigned char> vec;
for (auto buf = asio::dynamic_buffer(vec);
auto n = asio::read_until(socket, buf, ';');) {
std::cout << std::string_view(
asio::buffer_cast<char const*>(buf.data()), n)
<< std::endl;
buf.consume(n);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434927.html
上一篇:更改本地網路上網頁的url
下一篇:讀取呼叫會使執行速度減慢1分鐘?
