gpt4 book ai didi

c++ - boost read_some 函数丢失数据

转载 作者:行者123 更新时间:2023-11-28 07:31:05 25 4
gpt4 key购买 nike

我正在使用 boost asio 库实现一个 tcp 服务器。在服务器端,我使用asio::async_read_some获取数据,使用asio::write写入数据。服务器代码是这样的。

std::array<char, kBufferSize> buffer_;
std::string ProcessMessage(const std::string& s) {
if (s == "msg1") return "resp1";
if (s == "msg2") return "resp2";
return "";
}
void HandleRead(const boost::system::error_code& ec, size_t size) {
std::string message(buffer_.data(), size);
std::string resp = ProcessMessage(message);
if (!resp.empty()) {
asio::write(socket, boost::asio::buffer(message), WriteCallback);
}
socket.async_read_some(boost::asio::buffer(buffer_));
}

然后我写了一个客户端来测试服务端,代码是这样的

void MessageCallback(const boost::system::error_code& ec, size_t size) {
std::cout << string(buffer_.data(), size) << std::endl;
}
//Init socket
asio::write(socket, boost::asio::buffer("msg1"));
socket.read_some(boost::asio::buffer(buffer_), MessageCallback);
// Or async_read
//socket.async_read_some(boost::asio::buffer(buffer_), MessageCallback);
asio::write(socket, boost::asio::buffer("msg1"));
socket.read_some(boost::asio::buffer(buffer_), MessageCallback);
// Or async_read
//socket.async_read_some(boost::asio::buffer(buffer_), MessageCallback);

如果我运行客户端,代码将在第二个 read_some 处等待,输出为:resp1

如果我删除第一个 read_some,输出是 resp1resp2,这意味着服务器做了正确的事情。

似乎第一个 read_some EAT 第二个响应但不给 MessageCallback 函数响应。

我已经在 What is a message boundary? 阅读了问题,我认为如果这个问题是一个“消息边界”问题,第二个 read_some 应该打印一些东西,因为第一个 read_some 只从 tcp 套接字获取部分流。

我该如何解决这个问题?

更新:我尝试将客户端缓冲区的大小更改为 4,输出将是:

resp
resp

似乎 read_some 函数将做的不仅仅是从套接字读取,我将阅读 boost 代码以找出是否属实。

最佳答案

async_read_some()成员函数很可能没有按照您的意愿进行,请特别注意文档的备注部分

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

请注意,async_read() 自由函数确实提供了您正在寻找的保证

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

关于c++ - boost read_some 函数丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17691005/

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