读书人

socket http协议头有关问题

发布时间: 2012-10-29 10:03:53 作者: rapoo

socket http协议头问题

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <netinet/in.h>#include <unistd.h>#include <sys/socket.h>#include <string.h>int main(void) {    struct sockaddr_in sin;    struct sockaddr_in cin;    int lfd;    int afd;    socklen_t len;    char buf[1024];    bzero(&sin,sizeof(sin));    sin.sin_family = AF_INET;    sin.sin_port = htons(8001);    sin.sin_addr.s_addr = INADDR_ANY;    lfd = socket(AF_INET,SOCK_STREAM,0);    if(lfd < 0) {        perror("socket");        exit(1);    }    if(bind(lfd,(struct sockaddr *)&sin,sizeof(sin)) == -1) {        perror("bind");        exit(1);    }    listen(lfd,10);    while(1) {        afd = accept(lfd,(struct sockaddr *)&cin,&len);        if(afd < 0) {            perror("afd");            exit(1);        }        if(recv(afd,buf,1024,0) < 0) {            perror("recv");            exit(1);        }        printf("%s",buf);        write(afd,"HTTP/1.1 200 OK\r\n",strlen("HTTP/1.1 200 OK\r\n"));        write(afd,"<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>",strlen("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"));        write(afd,"<title>张三的第一个web服务器</title>",strlen("<title>张三的第一个web服务器</title>"));        write(afd,"<body><h1>大标题</h1><hr><h2>小标题</h2><div style='color:red'>红字</div></body></html>",strlen("<body><h1>大标题</h1><hr><h2>小标题</h2><div color = 'red'>红字</div></body></html>"));        fsync(afd);        close(afd);    }    return EXIT_SUCCESS;}

问题是,为什么返回了"http/1.1 200 ok\r\n"这句后,浏览器读不到下面的html代码

[解决办法]
1,write是否出错?
2,确保发送完毕后再关闭socket
3,其他接受端(比如curl)是否能收到?
[解决办法]
看了半天,没发现原因。

读书人网 >C语言

热点推荐