如何使用chunked-encoding发送HTTP回复?

时间:2011-02-28 13:36:10

标签: c linux http sockets chunked-encoding

大家好我正在尝试使用分块编码来传输多媒体数据。所以我首先尝试使用分块编码发送文本数据。

这是我的代码。我创建了一个服务器套接字,我在其上收听请求(端口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$

请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您的回答似乎缺少最终的CRLF序列。在响应中添加额外的\r\n应该更正此问题。