我构建了一个解析 header 的程序,我想在收到 POST 时读取消息正文。
对于 header ,我已经能够确定 header 何时结束。我对邮件正文有更多问题。我是否应该查看“内容长度”字段以了解何时停止读取输入?在我当前的代码(如下)中,直到我在 Firefox 中点击红叉(停止加载页面),它才会停止。
这是代码:
size_t n;
unsigned char newChar;
int index = 0;
int capacity = 50;
char *option = (char *) malloc(sizeof(char) * capacity);
while ( ( n = read( req->socket, &newChar, sizeof(newChar) ) ) > 0 ) {
if (newChar == '\0' || newChar == '\n') break; // This is not working
if (index == capacity) {
capacity *= 2;
option = (char *) realloc(option, sizeof(char) * capacity);
assert(option != NULL);
}
option[index++] = newChar;
fprintf(stderr, "%c", newChar);
}
if (index == capacity) {
capacity *= 2;
option = (char *) realloc(option, sizeof(char) * capacity);
assert(option != NULL);
}
option[index] = '\0';
正确的输入被打印出来,但我想知道为什么它不会停止,直到按下停止加载按钮。我想知道是否还有其他解决方案,或者我是否需要使用 header 中的“Content-Length”字段。
非常感谢,
贾里
最佳答案
有一些事情需要考虑。也许您需要考虑如何处理所有这些情况?
对于 HTTP 协议(protocol) 1.0,连接关闭用于表示数据结束。
HTTP 1.1 对此进行了改进,支持持久连接。对于 HTTP 1.1,通常您可以设置或读取 Content-Length header 来了解需要多少数据。
最后,在 HTTP 1.1 中,还可以使用“分块”模式,您可以在它们到来时获取大小,并且当发现 block Size == 0 时,您知道您已经到达末尾。
您还知道 libcurl ?它肯定会帮助您重新实现轮子。
关于c - HTTP协议(protocol): end of a message body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020106/