gpt4 book ai didi

c++ - Boost ASIO 将 X 字节同步读入 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:05 25 4
gpt4 key购买 nike

我一直在尝试使用 boost 编写一个客户端/服务器应用程序,到目前为止它发送和接收但我似乎不能只将 X 字节读入 vector 。

如果我使用下面的代码

vector<uint8_t> buf;

for (;;)
{
buf.resize(4);
boost::system::error_code error;

size_t len = socket.read_some(boost::asio::buffer(buf), error);

if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
}

数据包大于 4 个字节,然后它似乎一直写入这 4 个字节,直到收到整个数据包,但是我希望它获取 4 个字节,然后让我解析它们,然后获取其余部分数据包。

任何人都可以为我提供一个工作示例,或者至少提供有关如何使其正常工作的指导吗?

问候,施罗斯

最佳答案

你说套接字有超过 4 个字节可供读取,在这种情况下,你的代码正确地连续循环,因为在读取所有数据之前不会遇到 eof。在我看来,您想使用 read() 而不是 read_some() 因为后者返回的字节数可能少于您想要的四个字节。来自 read_some 文档。

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

您需要读取前 4 个字节(使用 read),处理它们(您不需要在循环中执行此操作),然后循环读取并处理数据,直到出现错误情况或eof。

我想你想要更多类似下面的内容:

vector<uint8_t> buf(4);
try
{
size_t len = read(socket, boost::asio::buffer(buf));
assert(len == 4);
// process the 4 bytes in buf
}
catch (boost::system::system_error &err)
{
// handle the error e.g by returning early
}

boost::system::error_code error;

while (!error)
{
size_t len = socket.read_some(boost::asio::buffer(buf), error);

  // process len bytes
}

关于c++ - Boost ASIO 将 X 字节同步读入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com