我正在从网络接收平面缓冲区对象,我正在使用文档建议的带前缀大小的缓冲区。在实际解散数据之前,我正在进行验证。问题是如何知道应该验证的缓冲区大小?
buff = recv(sock);
Verifier v(buff.data(), ???); // buffer could be half of a buffer or two buffers, what should I supply to the 2nd argument to Verifier?
bool f = VerifySizePrefixedMessageBuffer(v);
由于从网络接收的缓冲区可以是任何大小,因此它可以是平面缓冲区的一半或两个缓冲区,但是我将需要为Verifier提供一个消息缓冲区的大小。反正有这样做吗?
答案 0 :(得分:1)
You have to notify the receiver somehow, that the buffer sending is finished, and you should do that manualy.
If you use size-prefixed buffer approach, then the size of the buffer must be sent to the data receiver in the first bytes of the buffer. When the first buffer part is received, the receiver should read the data size from the first bytes of the received buffer and do recv()
until all data is transfered (until sum of all received buffer parts' sizes equals total size of the sent buffer, which you already know from the very first received buffer part).
On receiver side it should look like this:
buff = recv(sock);
uint32_t received = buff.size();
auto totalBuff = buff;
// I assume you have 4 bytes for unsigned integer buffer size prefix
while (received < 4) { // receive whole buffer size prefix data
buff = recv(sock);
received += buff.size();
// append new data to total data buffer
totalBuff.insert(totalBuff.end(), buff.begin(), buff.end());
}
uint32_t totalSize = *(reinterpret_cast<uint32_t>(totalBuff.data());
while (received < totalSize) {
buff = recv(sock);
received += buff.size();
// append new data to total data buffer
totalBuff.insert(totalBuff.end(), buff.begin(), buff.end());
}
// do whole buffer data processing
ProcessSizePrefixedBuffer(totalBuff);
In this totalBuff
data size will be in the first 4 bytes of the buffer. This is more pseudocode than working code, as I don't know your actual buff
type and other implementation details.