TinyHttpd(小型服务器程序)源码阅读记录

运行效果图

启动服务器

当有连接访问时

访问界面

代码详解

主要函数

void accept_request(void *); //接收请求并进行简单的处理
void bad_request(int); //返回400状态给客户端
void cat(int, FILE *); //读取文件发给客户端
void cannot_execute(int); //返回500状态给客户端
void error_die(const char *); //程序出错退出
void execute_cgi(int, const char *, const char *, const char *); //调整环境变量,执行cgi
int get_line(int, char *, int); //从套接字流中读取一行内容(一个字节一个字节的读)
void headers(int, const char *);//填充http响应头
void not_found(int); //返回404状态给客户端
void serve_file(int, const char *); //处理文件请求
int startup(u_short *); //初始化服务器监听套接字
void unimplemented(int); //返回501状态给客户端

代码(带有详细注释)

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <ctype.h>
#include <strings.h>
#include <string.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/wait.h>
#include <stdlib.h>

#define ISspace(x) isspace((int)(x))//如果x是一个空白字符,则该函数返回非零值(true),否则返回 0(false)。

#define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n"
#define STDIN   0
#define STDOUT  1
#define STDERR  2

void accept_request(void *); //接收请求并进行简单的处理
void bad_request(int); //返回400状态给客户端
void cat(int, FILE *); //读取文件发给客户端
void cannot_execute(int); //返回500状态给客户端
void error_die(const char *); //程序出错退出
void execute_cgi(int, const char *, const char *, const char *); //调整环境变量,执行cgi
int get_line(int, char *, int); //从套接字流中读取一行内容(一个字节一个字节的读)
void headers(int, const char *);//填充http响应头
void not_found(int); //返回404状态给客户端
void serve_file(int, const char *); //处理文件请求
int startup(u_short *); //初始化服务器监听套接字
void unimplemented(int); //返回501状态给客户端

/**********************************************************************/

 /*请求导致服务器端口上的调用被接受。适当地处理请求。参数:连接到客户端的套接字*/

/**********************************************************************/
void accept_request(void *arg)
{
    int client = *(int*)arg;
    char buf[1024];//读写用的缓冲区
    size_t numchars;//信号量
    char method[255];//请求方法
    char url[255];//统一资源定位符
    char path[512];//路径
    size_t i, j;
    struct stat st;//struct stat这个结构体是用来描述一个linux系统文件系统中的文件属性的结构
    int cgi = 0;      /* becomes true if server decides this is a CGI
                       * program */
    char *query_string = NULL;//请求行
//读http请求的第一行数据(request line),把请求方法存进method中
    numchars = get_line(client, buf, sizeof(buf));//从套接字流中读取一行内容(一个字节一个字节的读)到buf数组中
    i = 0; j = 0;
    while (!ISspace(buf[i]) && (i < sizeof(method) - 1))//请求方法读入method
    {
        method[i] = buf[i];
        i++;
    }
    j=i;
    method[i] = '\0';

    if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
    //strcasecmp(const char *s1, const char *s2)用来比较参数s1 和s2 字符串,比较时会自动忽略大小写的差异。相同返回0
    //如果请求方法既不是get也不是post就返回501状态给客户端
    {
        unimplemented(client);
        return;
    }
//如果是 POST 方法就将 cgi 标志变量置一(true)
    if (strcasecmp(method, "POST") == 0)
        cgi = 1;

    i = 0;
    //跳过空白字符
    while (ISspace(buf[j]) && (j < numchars))
        j++;
    //将url信息读入url数组
    while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
    {
        url[i] = buf[j];
        i++; j++;
    }
    url[i] = '\0';
//如果这个请求是一个 GET 方法的话
    if (strcasecmp(method, "GET") == 0)
    {
        //用一个指针指向 url
        query_string = url;
        //去遍历这个 url,跳过字符 ?前面的所有字符,如果遍历完毕也没找到字符 ?则退出循环
        while ((*query_string != '?') && (*query_string != '\0'))
            query_string++;
        //退出循环后检查当前的字符是 ?还是字符串(url)的结尾
        if (*query_string == '?')
        {
            //如果是 ? 的话,证明这个请求需要调用 cgi,将 cgi 标志变量置一(true)
            cgi = 1;
             //从字符 ? 处把字符串 url 给分隔会两份
            *query_string = '\0';
            query_string++;
        }
    }
/*srpintf()函数的功能非常强大:效率比一些字符串操作函数要高;
而且更具灵活性;可以将想要的结果输出到指定的字符串中,也可作为缓冲区,而printf只能输出到命令行上~
头文件:stdio.h
函数功能:格式化字符串,将格式化的数据写入字符串中。
函数原型:int sprintf(char *buffer, const char *format, [argument]...)
参数:
(1)buffer:是char类型的指针,指向写入的字符串指针;
(2)format:格式化字符串,即在程序中想要的格式;
(3)argument:可选参数,可以为任意类型的数据;
函数返回值:buffer指向的字符串的长度;
用处:
(1)格式化数字字符串:在这点上sprintf和printf的用法一样,只是打印到的位置不同而已,
前者打印给buffer字符串,后者打印给标准输出,所以sprintf也可以用来将整型转化为字符串,
比itoa效率高且如此地简便~比如:sprintf(buffer, "%d", 123456);执行后buffer即指向字符串“123456”~
(2)连接字符:*/

    //将前面分隔两份的前面那份字符串,拼接在字符串htdocs的后面之后就输出存储到数组 path 中。相当于现在 path 中存储着一个字符串
    sprintf(path, "htdocs%s", url);
    //如果 path 数组中的这个字符串的最后一个字符是以字符 / 结尾的话,就拼接上一个"index.html"的字符串。首页的意思
    if (path[strlen(path) - 1] == '/')
        strcat(path, "index.html");
    
    /*struct stat这个结构体是用来描述一个linux系统文件系统中的文件属性的结构
    获取一个文件的属性int stat(const char *path, struct stat *struct_stat);
    第一个参数都是文件的路径,第二个参数是struct stat的指针。
    返回值为0,表示成功执行。执行失败返回-1,error被自动设置为下面的值:
    EBADF: 文件描述词无效
    EFAULT: 地址空间不可访问
    ELOOP: 遍历路径时遇到太多的符号连接
    ENAMETOOLONG:文件路径名太长
    ENOENT:路径名的部分组件不存在,或路径名是空字串
    ENOMEM:内存不足
    ENOTDIR:路径名的部分组件不是目录 
    */
    //在系统上去查询该文件是否存在
    if (stat(path, &st) == -1) {
         //如果不存在,那把这次 http 的请求后续的内容(head 和 body)全部读完并忽略
        while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
            numchars = get_line(client, buf, sizeof(buf));
        //没有找到资源,返回404状态给客户端
        not_found(client);
    }
    else
    {
/* st_mode文件保护模式 
         
S_IFMT      0170000     文件类型的位遮罩
S_IFSOCK    0140000     socket
S_IFLNK     0120000     符号链接(symbolic link)
S_IFREG     0100000     一般文件
S_IFBLK     0060000     区块装置(block device)
S_IFDIR     0040000     目录
S_IFCHR     0020000     字符装置(character device)
S_IFIFO     0010000     先进先出(fifo)
S_ISUID     0004000     文件的(set user-id on execution)位
S_ISGID     0002000     文件的(set group-id on execution)位
S_ISVTX     0001000     文件的sticky位
S_IRWXU     00700       文件所有者的遮罩值(即所有权限值)
S_IRUSR     00400       文件所有者具可读取权限
S_IWUSR     00200       文件所有者具可写入权限
S_IXUSR     00100       文件所有者具可执行权限
S_IRWXG     00070       用户组的遮罩值(即所有权限值)
S_IRGRP     00040       用户组具可读取权限
S_IWGRP     00020       用户组具可写入权限
S_IXGRP     00010       用户组具可执行权限
S_IRWXO     00007       其他用户的遮罩值(即所有权限值)
S_IROTH     00004       其他用户具可读取权限
S_IWOTH     00002       其他用户具可写入权限
S_IXOTH     00001       其他用户具可执行权限
*/

//文件存在,那去跟常量S_IFMT相与,相与之后的值可以用来判断该文件是什么类型的
//S_IFMT参读《TLPI》P281,与下面的三个常量一样是包含在<sys/stat.h>
        if ((st.st_mode & S_IFMT) == S_IFDIR)
            //如果这个文件是个目录,那就需要再在 path 后面拼接一个"/index.html"的字符串
            strcat(path, "/index.html");
        if ((st.st_mode & S_IXUSR) ||
                (st.st_mode & S_IXGRP) ||
                (st.st_mode & S_IXOTH)    )
             //如果这个文件是一个可执行文件,不论是属于用户/组/其他这三者类型的,就将 cgi 标志变量置一
            cgi = 1;
        //如果不需要 cgi 机制的话,
        if (!cgi)
            serve_file(client, path);////处理文件请求
        else
        //如果需要则调用
            execute_cgi(client, path, method, query_string);////调整环境变量,执行cgi
    }
    close(client);
}

/**********************************************************************/
 //返回400状态给客户端
 //参数:客户端套接字
/**********************************************************************/

void bad_request(int client)
{
    char buf[1024];

    sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
    send(client, buf, sizeof(buf), 0);
    sprintf(buf, "Content-type: text/html\r\n");
    send(client, buf, sizeof(buf), 0);
    sprintf(buf, "\r\n");
    send(client, buf, sizeof(buf), 0);
    sprintf(buf, "<P>Your browser sent a bad request, ");
    send(client, buf, sizeof(buf), 0);
    sprintf(buf, "such as a POST without a Content-Length.\r\n");
    send(client, buf, sizeof(buf), 0);
}

/**********************************************************************/
 /* 在套接字上显示文件的全部内容。这个函数是以unix的cat命令命名的
 ,因为做一些像管道、叉子和执行cat之类的事情可能比较容易。
 参数:客户端套接字描述器。文件指针为cat */
/**********************************************************************/
void cat(int client, FILE *resource)
{
    char buf[1024];
 //从文件文件描述符中读取指定内容
    fgets(buf, sizeof(buf), resource);
    while (!feof(resource))
    {
        send(client, buf, strlen(buf), 0);
        fgets(buf, sizeof(buf), resource);
    }
}

/**********************************************************************/
 /*通知客户端cgi脚本无法执行。参数:客户端套接字描述符。*/
/**********************************************************************/
void cannot_execute(int client)
{
    char buf[1024];

    sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "Content-type: text/html\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
    send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
 /*打印出带有perror()的错误消息(用于系统错误;基于errno的值,该值表示系统调用错误),
 并退出表示错误的程序。*/
/**********************************************************************/
void error_die(const char *sc)
{
    perror(sc);
    exit(1);
}

/**********************************************************************/
 /*执行cgi脚本。将需要酌情设置环境变量。
   cgi脚本的路径*/
/**********************************************************************/
void execute_cgi(int client, const char *path,
        const char *method, const char *query_string)
{
    char buf[1024];
    int cgi_output[2];
    int cgi_input[2];
    pid_t pid;
    int status;
    int i;
    char c;
    int numchars = 1;
    int content_length = -1;
     //往 buf 中填东西以保证能进入下面的 while
    buf[0] = 'A'; buf[1] = '\0';
     //如果是 http 请求是 GET 方法的话读取并忽略请求剩下的内容
    if (strcasecmp(method, "GET") == 0)
        while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
            numchars = get_line(client, buf, sizeof(buf));
    else if (strcasecmp(method, "POST") == 0) /*POST*/
    {
        //只有 POST 方法才继续读内容
        numchars = get_line(client, buf, sizeof(buf));
        //这个循环的目的是读出指示 body 长度大小的参数,并记录 body 的长度大小。其余的 header 里面的参数一律忽略
        //注意这里只读完 header 的内容,body 的内容没有读
        while ((numchars > 0) && strcmp("\n", buf))
        {
            buf[15] = '\0';
            if (strcasecmp(buf, "Content-Length:") == 0)
                content_length = atoi(&(buf[16]));//记录 body 的长度大小
            numchars = get_line(client, buf, sizeof(buf));
        }
        //如果 http 请求的 header 没有指示 body 长度大小的参数,则报错返回
        if (content_length == -1) {
            bad_request(client);
            return;
        }
    }
    else/*HEAD or other*/
    {
    }
/*
服务器从URL中获取cgi的名字,然后fork一个子进程,设置好
环境变量和管道(使用dup2函数将STDIN、STDOUT重定向到管道)之后,
使用exec系列函数运行cgi程序。cgi程序可以从STDIN或环境变量表中
读取数据,然后把结果写到STDOUT就完事了。 
而服务器会从管道读取cgi程序的处理结果,返回给浏览器。
*/

 //下面这里创建两个管道,用于两个进程间通信

    if (pipe(cgi_output) < 0) {
        cannot_execute(client);
        return;
    }
    if (pipe(cgi_input) < 0) {
        cannot_execute(client);
        return;
    }
 //创建一个子进程
    if ( (pid = fork()) < 0 ) {
        cannot_execute(client);
        return;
    }
    sprintf(buf, "HTTP/1.0 200 OK\r\n");
    send(client, buf, strlen(buf), 0);
    //子进程用来执行 cgi 脚本
    if (pid == 0)  /* child: CGI script */
    {
        char meth_env[255];
        char query_env[255];
        char length_env[255];
        //将子进程的输出由标准输出重定向到 cgi_ouput 的管道写端上
        dup2(cgi_output[1], STDOUT);
         //将子进程的输出由标准输入重定向到 cgi_ouput 的管道读端上
        dup2(cgi_input[0], STDIN);
         //关闭 cgi_ouput 管道的读端与cgi_input 管道的写端
        close(cgi_output[0]);
        close(cgi_input[1]);
        //构造一个环境变量
        sprintf(meth_env, "REQUEST_METHOD=%s", method);
          //将这个环境变量加进子进程的运行环境中
        putenv(meth_env);
          //根据http 请求的不同方法,构造并存储不同的环境变量
        if (strcasecmp(method, "GET") == 0) {
            sprintf(query_env, "QUERY_STRING=%s", query_string);
            putenv(query_env);
        }
        else {   /* POST */
            sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
            putenv(length_env);
        }
         //最后将子进程替换成另一个进程并执行 cgi 脚本
        execl(path, NULL);
        exit(0);
    } else {    /* parent */
    //父进程则关闭了 cgi_output管道的写端和 cgi_input 管道的读端
        close(cgi_output[1]);
        close(cgi_input[0]);
        if (strcasecmp(method, "POST") == 0)
            for (i = 0; i < content_length; i++) {
                recv(client, &c, 1, 0);
                write(cgi_input[1], &c, 1);
            }
        //然后从 cgi_output 管道中读子进程的输出,并发送到客户端去
        while (read(cgi_output[0], &c, 1) > 0)
            send(client, &c, 1, 0);
        //关闭管道
        close(cgi_output[0]);
        close(cgi_input[1]);
         //等待子进程的退出
        waitpid(pid, &status, 0);
    }
}

/***********************************************************************/
/*
函数原型:int recv( SOCKET s, char *buf, int  len, int flags)

功能:不论是客户还是服务器应用程序都用recv函数从TCP连接的另一端接收数据。
参数一:指定接收端套接字描述符;
参数二:指明一个缓冲区,该缓冲区用来存放recv函数接收到的数据;
参数三:指明buf的长度;
参数四 :一般置为0。

阻塞与非阻塞recv返回值没有区分,都是
 >  0  成功接收数据大小。
 =  0  另外一端关闭了套接字
 = -1     错误,需要获取错误码errno(win下是通过WSAGetLastError())
*/
*****************************************************************/
int get_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;

    while ((i < size - 1) && (c != '\n'))
    {
        n = recv(sock, &c, 1, 0);
        /* DEBUG printf("%02X\n", c); */
        if (n > 0)
        {
            if (c == '\r')//如果是回车符,继续判断下一个字符,如果下一个字符是换行符,c=再下一个字符,否则c='\0'
            {
                n = recv(sock, &c, 1, MSG_PEEK);
                /*MSG_PEEK标志会将套接字接收队列中的可读的数据拷
                贝到缓冲区,但不会使套接子接收队列中的数据减少*/
                /* DEBUG printf("%02X\n", c); */
                if ((n > 0) && (c == '\n'))
                    recv(sock, &c, 1, 0);
                else
                    c = '\n';
            }
            buf[i] = c;
            i++;
        }
        else
            c = '\n';//如果读取失败则c='\n'
    }
    buf[i] = '\0';//添加'\0'结尾

    return(i);
}

/**********************************************************************/
 /*返回关于文件的信息http标头。
 参数:要在文件名称上打印页眉的套接字*/
/**********************************************************************/
void headers(int client, const char *filename)
{
    char buf[1024];
    (void)filename;  /* could use filename to determine file type */

    strcpy(buf, "HTTP/1.0 200 OK\r\n");
    send(client, buf, strlen(buf), 0);
    strcpy(buf, SERVER_STRING);//SERVER_STRING="Server: jdbhttpd/0.1.0\r\n"
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "Content-Type: text/html\r\n");
    send(client, buf, strlen(buf), 0);
    strcpy(buf, "\r\n");
    send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
////返回400状态给客户端
/**********************************************************************/
void not_found(int client)
{
    char buf[1024];

    sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, SERVER_STRING);
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "Content-Type: text/html\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "your request because the resource specified\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "is unavailable or nonexistent.\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "</BODY></HTML>\r\n");
    send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
/* Send a regular file to the client.  Use headers, and report
 * errors to client if they occur.
 * Parameters: a pointer to a file structure produced from the socket
 *              file descriptor
 *             the name of the file to serve */
/**********************************************************************/
void serve_file(int client, const char *filename)
{
    FILE *resource = NULL;
    int numchars = 1;
    char buf[1024];
    //确保 buf 里面有东西,能进入下面的 while 循环
    buf[0] = 'A'; buf[1] = '\0';
    //循环作用是读取并忽略掉这个 http 请求后面的所有内容
    while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
        numchars = get_line(client, buf, sizeof(buf));
    //打开这个传进来的这个路径所指的文件
    resource = fopen(filename, "r");
    if (resource == NULL)
        not_found(client);
    else
    {
        //打开成功后,将这个文件的基本信息封装成 response 的头部(header)并返回
        headers(client, filename);
         //接着把这个文件的内容读出来作为 response 的 body 发送到客户端
        cat(client, resource);
    }
    fclose(resource);
}

/**********************************************************************/
/*
 此函数启动在指定端口上监听网络连接的过程。如果端口为0,
 则动态分配一个端口并修改原始端口变量以反映实际端口。
 参数:指针指向包含端口的变量,以返回连接:套接字
 */
/**********************************************************************/
/***************************************************************************/
/* typedef unsigned short sa_family_t;
struct sockaddr {
        sa_family_t     sa_family;    //address family, AF_xxx       
        char            sa_data[14];   //  14 bytes of protocol address 
};
/***********ipv4的套接字地址*********************************/
/*
struct sockaddr_in {
  __kernel_sa_family_t sin_family; // AF_INET short int
  __be16 sin_port; // Port number 端口号 unsigned short int
  struct in_addr sin_addr; // Internet address 32位unsigned int ipv4 网络地址

  //Pad to size of `struct sockaddr'.结构体sockaddr_in的size
  unsigned char __pad[__SOCK_SIZE__ - sizeof(short int) -
                        sizeof(unsigned short int) - sizeof(struct in_addr)];
}; 
*/
/*
socket(PF_INET, SOCK_STREAM,0)---TCP连接 或socket(AF_INET, SOCK_STREAM,0)---UDP连接
socket()系统调用,带有三个参数: 
1、参数domain指明通信域,如PF_UNIX(unix域),PF_INET(IPv4),PF_INET6(IPv6)等
2、type 指明通信类型,最常用的如SOCK_STREAM(面向连接可靠方式,  比如TCP)、SOCK_DGRAM(非面向连接的非可靠方式,比如
UDP)等。  SOCK_STREAM 是数据流,一般是tcp/ip协议的编程,SOCK_DGRAM分是数据抱,是udp协议网络编程。
3、参数protocol指定需要使用的协议。虽然可以对同一个协议  家族(protocol family)(或者说通信域(domain))指定不同的协议  参数, 
但是通常只有一个。对于TCP参数可指定为IPPROTO_TCP,对于  UDP可以用IPPROTO_UDP。你不必显式制定这个参数,使用0则根据前
两个参数使用默认的协议

返回值:如果函数调用成功,会返回一个标识这个套接字的文件描述符,失败的时候返回-1。
*/
int startup(u_short *port)
{
    int httpd = 0;
     //sockaddr_in 是 IPV4的套接字地址结构。
    struct sockaddr_in name;
    //socket()用于创建一个用于 socket 的描述符,函数包含于<sys/socket.h>
    //这里的PF_INET其实是与 AF_INET同义
    httpd = socket(PF_INET, SOCK_STREAM, 0);
    if (httpd == -1)
        error_die("socket");
    memset(&name, 0, sizeof(name));
    name.sin_family = AF_INET;
    //htons(),ntohs() 和 htonl()包含于<arpa/inet.h>
    //将*port 转换成以网络字节序表示的16位整数
    name.sin_port = htons(*port);
    //INADDR_ANY是一个 IPV4通配地址的常量,包含于<netinet/in.h>
    //大多实现都将其定义成了0.0.0.0 
    if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
        error_die("bind");
    //如果调用 bind 后端口号仍然是0,则手动调用getsockname()获取端口号
    if (*port == 0)  /* if dynamically allocating a port */
    {
        
        socklen_t namelen = sizeof(name);
        //getsockname()包含于<sys/socker.h>中,参读《TLPI》P1263
        //调用getsockname()获取系统给 httpd 这个 socket 随机分配的端口号
        if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
            error_die("getsockname");
        *port = ntohs(name.sin_port);
    }
    if (listen(httpd, 5) < 0)
        error_die("listen");
    return(httpd);
}

/**********************************************************************/
 //返回501状态给客户端(服务器发生错误)
/**********************************************************************/
void unimplemented(int client)
{
    char buf[1024];

    sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, SERVER_STRING);
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "Content-Type: text/html\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "</TITLE></HEAD>\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
    send(client, buf, strlen(buf), 0);
    sprintf(buf, "</BODY></HTML>\r\n");
    send(client, buf, strlen(buf), 0);
}

/**********************************************************************/

int main(void)
{
    int server_sock = -1;
    u_short port = 4000;
    int client_sock = -1;
    struct sockaddr_in client_name;
    socklen_t  client_name_len = sizeof(client_name);
    pthread_t newthread;

    server_sock = startup(&port);
    printf("httpd running on port %d\n", port);
    //阻塞等待客户端的连接
    while (1)
    {
        client_sock = accept(server_sock,
                (struct sockaddr *)&client_name,
                &client_name_len);
        if (client_sock == -1)
            error_die("accept");
        /* accept_request(client_sock); */
        if (pthread_create(&newthread , NULL, (void *)accept_request, (void *)&client_sock) != 0)
            perror("pthread_create");
    }

    close(server_sock);

    return(0);
}

猜你喜欢

转载自blog.csdn.net/sinat_40766770/article/details/84895342