在 Linux 上,您可以使用MSG_WAITALL
选项 for recv()
,这使函数等待完整的给定长度的传入数据。
作为替代方案(在所有平台上工作),您还可以编写一个接收给定字节数的通用接收函数,例如这个(假设套接字未设置为非阻塞;需要包括<stdint.h>
):
/// \brief Receives a block of data of the specified size
/// \param sk Socket for incoming data
/// \param data Pointer to input buffer
/// \param len Number of bytes to read
/// \return Number of bytes received (same as len) on success, -1 on failure
int block_recv(const int sk, uint8_t* data, unsigned int len)
{
int i, j = 0;
while (len > 0) {
i = recv(sk, (char*) data, len, 0);
if (i <= 0) {
return -1;
}
data += i;
len -= i;
j += i;
}
return j;
}
然后你可以调用它来接收你的整数缓冲区:
if (block_recv(fd, (uint8_t*) msg, sizeof(msg)) != sizeof(msg)) {
fprintf(stderr, "Error receiving integer buffer...\n");
// whatever error handling you need...
}