Handling partial return from recv() TCP in C(在 C 中处理从 recv() TCP 的部分返回)
问题描述
我一直在阅读Beej 的网络编程指南获取 TCP 连接的句柄.在其中一个示例中,简单 TCP 流客户端的客户端代码如下所示:
I've been reading through Beej's Guide to Network Programming to get a handle on TCP connections. In one of the samples the client code for a simple TCP stream client looks like:
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = ' ';
printf("Client: received '%s'
", buf);
close(sockfd);
我已将缓冲区设置为小于我发送的总字节数.我不太确定如何获得其他字节.我是否必须遍历 recv()
直到收到 ' '
?
I've set the buffer to be smaller than the total number of bytes that I'm sending. I'm not quite sure how I can get the other bytes. Do I have to loop over recv()
until I receive ' '
?
*注意在服务器端,我也在实现他的 sendall()
函数,所以它实际上应该将所有内容发送到客户端.
*Note on the server side I'm also implementing his sendall()
function, so it should actually be sending everything to the client.
另见6.1.指南中的简单流服务器.
推荐答案
是的,您将需要多次 recv()
调用,直到您拥有所有数据.
Yes, you will need multiple recv()
calls, until you have all data.
要知道那是什么时候,使用 recv()
的返回状态是不好的 - 它只告诉您收到了多少字节,而不是可用字节数,因为有些可能仍然在途中.
To know when that is, using the return status from recv()
is no good - it only tells you how many bytes you have received, not how many bytes are available, as some may still be in transit.
如果您收到的数据以某种方式对总数据的长度进行编码会更好.读取尽可能多的数据直到您知道长度是多少,然后读取直到您收到length
数据.为此,可以采用各种方法;常见的做法是,一旦知道长度是多少,就制作一个足够大的缓冲区来容纳所有数据.
It is better if the data you receive somehow encodes the length of the total data. Read as many data until you know what the length is, then read until you have received length
data. To do that, various approaches are possible; the common one is to make a buffer large enough to hold all data once you know what the length is.
另一种方法是使用固定大小的缓冲区,并且总是尝试接收min(missing, bufsize)
,在每个recv()<之后减少
missing
/代码>.
Another approach is to use fixed-size buffers, and always try to receive min(missing, bufsize)
, decreasing missing
after each recv()
.
这篇关于在 C 中处理从 recv() TCP 的部分返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C 中处理从 recv() TCP 的部分返回


基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01