问题描述
我一直在阅读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 的部分返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)