【发布时间】:2022-02-24 23:52:27
【问题描述】:
我正在从 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
我哪里错了?
谢谢!
【问题讨论】:
-
嗨,这似乎建议使用 getline,就像我上面的代码一样。
-
查看答案。他们使用
async_read_until。问题不是答案。 -
道歉。我试图了解如何使用这个函数,但我能找到的最简单的例子是:`std::vector
buffer; asio::async_read_until(socket, asio::dynamic_buffer(buffer, 16), ';', [&](asio::error_code error, std::size_t bytes_transferred); { std::cout -
The first answer 展示了如何使用分隔符。
标签: c++ sockets boost-asio