gpt4 book ai didi

c - 如何使用分块编码发送 HTTP 回复?

转载 作者:可可西里 更新时间:2023-11-01 17:14:59 28 4
gpt4 key购买 nike

大家好,我正在尝试使用分块编码流式传输多媒体数据。因此,我首先尝试使用分块编码发送文本数据。

这是我的代码。我创建了一个服务器套接字,我在上面监听请求(端口 80),回复请求,然后我的程序终止。无论您提出什么要求,您总是会得到相同的答复。在我的机器上,我发送“http://localhost/anirudh.html”作为浏览器的请求。输出显示数据包已发送,但在浏览器上没有显示任何内容。我在某个地方犯了一个错误,因为我不知道如何正确使用分块编码发送回复,所以我无法找出错误。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<fcntl.h>

int main(){

struct sockaddr_in sockserv,sockclient;
int socketfd,clientfd;
socklen_t clientsocklen;
int filefd;
int finalcnt = 0;

char buff[BUFSIZ];

socketfd = socket(AF_INET,SOCK_STREAM,0);
printf("Socket Creation: %s\n",strerror(errno));

bzero(&sockserv,sizeof(sockserv));

sockserv.sin_family = AF_INET;
sockserv.sin_addr.s_addr = INADDR_ANY;
sockserv.sin_port = htons(80);

bind(socketfd,(struct sockaddr *)&sockserv,sizeof(sockserv));
printf("Socket Bind: %s\n",strerror(errno));

listen(socketfd,10);
printf("Socket Listen: %s\n",strerror(errno));

clientfd = accept(socketfd,(struct sockaddr*)&sockclient,&clientsocklen);
printf("request accepted\n");

buff[read(clientfd,buff,BUFSIZ)] = '\0';
printf("Request recieved as \n%s\n",buff);

sprintf(buff,"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nDate: Mon, 28 Feb 2011 10:38:19 GMT\r\nTransfer-Encoding: chunked\r\nServer: Myserver\r\n\r\n%x\r\n%s\r\n0\r\n",strlen("<html><body><p> HI I am anirudh tomer </p> </body></html>"),"<html><body><p> HI I am anirudh tomer </p> </body></html>");

printf("\n\nREPLY TO THE CLIENT\n\n%s\n\n",buff);

finalcnt = send(clientfd,buff,strlen(buff),0);
printf("Sent %d bytes to the client : %s\n",finalcnt,strerror(errno));

close(clientfd);
close(socketfd);

return 0;
}

回复如下:

anirudh@anirudh-Aspire-5920:~/Desktop/testing$ gcc test.c
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo ./a.out
Socket Creation: Success
Socket Bind: Success
Socket Listen: Success
request accepted
Request recieved as
GET /avashjfvjhaasadjfasafa.ogg HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3




REPLY TO THE CLIENT

HTTP/1.1 200 OK
Content-Type: text/html
Date: Mon, 28 Feb 2011 10:38:19 GMT
Transfer-Encoding: chunked
Server: Myserver

39
<html><body><p> HI I am anirudh tomer </p> </body></html>
0


Sent 193 bytes to the client : Success
anirudh@anirudh-Aspire-5920:~/Desktop/testing$

请帮帮我。提前致谢。

最佳答案

您的回复似乎缺少最终的 CRLF 序列。在响应中添加额外的 \r\n 应该可以解决这个问题。

关于c - 如何使用分块编码发送 HTTP 回复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5142649/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com