C:解决在 HTTP 上下文中使用 select 时出现部分标头的情况

发布于 2024-08-19 19:57:53 字数 594 浏览 11 评论 0原文

这是参考我之前已经回答的问题:

C:使用 select 调用,当我阅读时,如何跟踪数据?

我的协议实际上发送了多少数据是关于在发送任何其他数据之前首先发送的。但是昨天,当我使用浏览器测试我的这段代码时,我有一个问题:

很多人建议我检查消息长度,但以浏览器的场景为例。浏览器的HTTP请求在第一次发送到服务器时没有大小。现在,假设我使用了 256 字节缓冲区,如果我在每个多路复用操作之间不断接收部分标头,我应该如何管理该客户端的数据结构?继续使用 realloc,因为我不断获取更多数据,然后当我遇到终止序列('\r\n')时,假设已收到所有数据?

我的意思是,有这样的东西:

typedef struct {
   int fd;
   char *data;
} CLIENT;

然后继续对数据使用 realloc?有人告诉我分配最大协议头的缓冲区大小,但这是唯一的方法吗?

This is in reference to a previous question of mine which was already answered:

C: Using a select call, when I am reading, how do I keep track of the data?

My protocol actually sends how much data it is about send initially before it sends any other data. But yesterday, when testing out this code of mine using a browser, I had this one question:

A lot of people suggested that I check for message length but take the scenario of a browser. The browser's HTTP Request does not have a size when it is first sent to the server. Now, assuming that I used a 256 byte buffer, how am I supposed to manage the data structure of this client if I keep receiving partial headers between each multiplexing action? Keep using realloc as I keep getting more data and then when I encounter a termination sequence ('\r\n'), assume that all data has been received?

What I mean is, have something like this:

typedef struct {
   int fd;
   char *data;
} CLIENT;

And then keep using realloc on data? I was told to allocate a buffer size of the max protocol header but is that the only approach?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时间你老了 2024-08-26 19:57:53

重新分配缓冲区的大小就可以了。我会选择至少比 256 - 1024 或 4096 大一点的缓冲区。分配像 HTTP 这样的协议的最大缓冲区大小实际上并不可行。您还可以在缓冲区顶部构建一个能够读取行的抽象 - 就像 fgets 在 FILE* 上所做的那样。

请记住,读取块可能会读取 HTTP 标头的最后部分和 HTTP 正文的一部分,如果有任何 ,因此您需要确保正确地对缓冲区进行切片,因为您可能希望将标头与正文分开。您还必须查找 Content-Length: 标头,对其进行解析,以便知道正文的长度。

reallocing the buffer in sizes is fine. I'd pick a bit larger buffer than 256 - 1024 atleast or 4096. Allocating a max buffer size of a protocol like HTTP is not really feasible. You could also build an abstraction on top of your buffer that are able to read lines - much like fgets does on a FILE*

Keep in mind that reading a chunk might read the last part of the HTTP headers and a piece of the HTTP body if there's any , so you need to make sure you slice the buffer properly as you likely want to seperate the header from the body. You'll also have to look for the Content-Length: header, parse that, so you know how long the body will be.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文