处理来自的recv()TCP用C部分收益 [英] Handling partial return from recv() TCP in C

查看:85
本文介绍了处理来自的recv()TCP用C部分收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在读通过的 Beej的指南网络编程 的到获得TCP连接的手柄。在客户端code代表一个简单的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] = '\0';

printf("Client: received '%s'\n", buf);

close(sockfd);

我已经设置缓冲区比我送的总字节数小。我不太肯定我怎么能得到其他字节。我必须遍历的recv(),直到我收到'\\ 0'

*注意在服务器端,我也实现了 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。一个简单的流服务器 的指南中

See also 6.1. A Simple Stream Server in the guide.

推荐答案

是的,你需要多个的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.

这是更好,如果数据您会收到莫名其妙的连接codeS的总数据的长度。直到你知道什么长度,然后读取您收到长度数据,直到读尽可能多的数据。要做到这一点,各种方法都是可能的;常见之一就是让大到足以容纳所有数据的缓冲区,一旦你知道的长度是什么。

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.

另一种方法是使用固定大小的缓冲区,并总是试图获得分(缺失,BUFSIZE),降低缺少每个的recv()之后,

Another approach is to use fixed-size buffers, and always try to receive min(missing, bufsize), decreasing missing after each recv().

这篇关于处理来自的recv()TCP用C部分收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆