在 C 中处理从 recv() TCP 的部分返回

Handling partial return from recv() TCP in C(在 C 中处理从 recv() TCP 的部分返回)
本文介绍了在 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 的部分返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)